Skip to content

Commit

Permalink
Merge pull request #502 from onyxfish/366
Browse files Browse the repository at this point in the history
Fix #366
  • Loading branch information
James McKinney committed Jan 23, 2016
2 parents 120db72 + ef77b5b commit 6dd8c34
Show file tree
Hide file tree
Showing 5 changed files with 49 additions and 4 deletions.
1 change: 1 addition & 0 deletions AUTHORS
Expand Up @@ -61,3 +61,4 @@ The following individuals have contributed code to csvkit:
* Eric Bréchemier
* Neil Freeman
* Fede Isas
* Patricia Lipp
11 changes: 7 additions & 4 deletions csvkit/convert/js.py
Expand Up @@ -10,6 +10,7 @@
import agate
import six


def parse_object(obj, path=''):
"""
Recursively parse JSON objects and a dictionary of paths/keys and values.
Expand All @@ -21,16 +22,17 @@ def parse_object(obj, path=''):
elif isinstance(obj, (list, tuple)):
iterator = enumerate(obj)
else:
return { path.strip('/'): obj }
return {path.strip('/'): obj}

d = {}
d = OrderedDict()

for key, value in iterator:
key = six.text_type(key)
d.update(parse_object(value, path + key + '/'))

return d


def json2csv(f, key=None, **kwargs):
"""
Convert a JSON document into CSV format.
Expand All @@ -49,9 +51,10 @@ def json2csv(f, key=None, **kwargs):
flat = []

for obj in js:
flat.append(parse_object(obj))
parsed_object = parse_object(obj)
flat.append(parsed_object)

for key in obj.keys():
for key in parsed_object.keys():
if key not in fields:
fields.append(key)

Expand Down
28 changes: 28 additions & 0 deletions examples/testjson_nested.json
@@ -0,0 +1,28 @@
[
{
"text": "Chicago Reader",
"float": 1.0,
"datetime": "1971-01-01T04:14:00",
"boolean": true,
"nested": {
"time": "04:14:00",
"nested": {
"date": "1971-01-01",
"integer": 40
}
}
},
{
"text": "Chicago Sun-Times",
"float": 1.27,
"datetime": "1948-01-01T14:57:13",
"boolean": true,
"nested": {
"time": "14:57:13",
"nested": {
"date": "1948-01-01",
"integer": 63
}
}
}
]
3 changes: 3 additions & 0 deletions examples/testjson_nested_converted.csv
@@ -0,0 +1,3 @@
text,float,datetime,boolean,nested/time,nested/nested/date,nested/nested/integer
Chicago Reader,1.0,1971-01-01T04:14:00,True,04:14:00,1971-01-01,40
Chicago Sun-Times,1.27,1948-01-01T14:57:13,True,14:57:13,1948-01-01,63
10 changes: 10 additions & 0 deletions tests/test_utilities/test_in2csv.py
Expand Up @@ -70,3 +70,13 @@ def test_convert_ndjson(self):

target_output = open('examples/testjson_multiline_converted.csv', 'r').read()
self.assertEqual(output_file.getvalue(), target_output)

def test_convert_nested_json(self):
args = ['examples/testjson_nested.json']
output_file = six.StringIO()

utility = In2CSV(args, output_file)
utility.main()

target_output = open('examples/testjson_nested_converted.csv', 'r').read()
self.assertEqual(output_file.getvalue(), target_output)

0 comments on commit 6dd8c34

Please sign in to comment.