Reputation: 17049
I have a file with JSON:
{
"first":{"a":[{"b":[{"c":"AAA"}]}],"d":111},
"second":{"a":[{"b":[{"c":"BBB"},{"c":"CCC"}]}],"d":222}
}
I need to save it with flat text structure, something like that:
111
AAA
222
BBB
CCC
How do I iterate through JSON? All I've managed to do is:
import json
file_json = open('1.txt', mode='r', encoding='utf-8')
data = json.load(file_json)
file_json.close()
file_new = open('data.txt', mode='w', encoding='utf-8')
for number in data:
file_new.write(number + "\n")
file_new.close()
I get
first
second
But how do I get rest of the data?
I tried for number, data_rest in data:
, but it get ValueError: too many values to unpack (expected 2)
.
Upvotes: 0
Views: 474
Reputation: 310187
For this particular structure, you can get the elements you're looking for from
>>> d = {
... "first":{"a":[{"b":[{"c":"AAA"}]}],"d":111},
... "second":{"a":[{"b":[{"c":"BBB"},{"c":"CCC"}]}],"d":222}
... }
>>> d['first']['d']
111
>>> import itertools
>>> list(itertools.chain.from_iterable(x.values() for x in d['first']['a'][0]['b']))
['AAA']
>>> list(itertools.chain.from_iterable(x.values() for x in d['second']['a'][0]['b']))
['BBB', 'CCC']
When you're all said and done, it might look something like this:
from itertools import chain
import json
s = '''{
"first":{"a":[{"b":[{"c":"AAA"}]}],"d":111},
"second":{"a":[{"b":[{"c":"BBB"},{"c":"CCC"}]}],"d":222}
}'''
from collections import OrderedDict
d = json.loads(s,object_pairs_hook=OrderedDict) #Keep order of dictionaries
for subdict in d.values():
print subdict['d']
chained = chain.from_iterable(x.values() for x in subdict['a'][0]['b'])
for item in chained:
print '\t',item
Upvotes: 1