From c3f650ca06cfca1741035509c46a20fbd3620e6d Mon Sep 17 00:00:00 2001 From: Yaniv Aknin Date: Thu, 25 Apr 2024 06:24:37 +0100 Subject: [PATCH] Fix fromjson() to support reading from stdin --- petl/io/json.py | 2 +- petl/test/test_executable.py | 12 ++++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/petl/io/json.py b/petl/io/json.py index 75600e6c..f7b8c39c 100644 --- a/petl/io/json.py +++ b/petl/io/json.py @@ -16,7 +16,7 @@ from petl.util.base import data, Table, dicts as _dicts, iterpeek -def fromjson(source, *args, **kwargs): +def fromjson(source=None, *args, **kwargs): """ Extract data from a JSON file. The file must contain a JSON array as the top level object, and each member of the array will be treated as a diff --git a/petl/test/test_executable.py b/petl/test/test_executable.py index 1b8645f4..8230f2ff 100644 --- a/petl/test/test_executable.py +++ b/petl/test/test_executable.py @@ -8,3 +8,15 @@ def test_executable(): petl 'fromcsv().cut("foo").head(1).tocsv()' """, shell=True, check=True, capture_output=True) assert result.stdout == b'foo\r\na\r\n' + +def test_json_stdin(): + result = subprocess.run(""" + echo '[{"foo": "a", "bar": "b"}]' | + petl 'fromjson().tocsv()' + """, shell=True, check=True, capture_output=True) + assert result.stdout == b'foo,bar\r\na,b\r\n' + result = subprocess.run(""" + ( echo '{"foo": "a", "bar": "b"}' ; echo '{"foo": "c", "bar": "d"}' ) | + petl 'fromjson(lines=True).tocsv()' + """, shell=True, check=True, capture_output=True) + assert result.stdout == b'foo,bar\r\na,b\r\nc,d\r\n'