我有一个JSON文件:
{
"first":{"a":[{"b":[{"c":"AAA"}]}],"d":111},
"second":{"a":[{"b":[{"c":"BBB"},{"c":"CCC"}]}],"d":222}
}
我需要将其保存为平面文本结构,就像这样:
111
AAA
222
BBB
CCC
如何遍历JSON?我所能做的就是:
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()
我first
second
但是我怎么得到剩下的数据呢?
我试了for number, data_rest in data:
,但它得到了ValueError: too many values to unpack (expected 2)
。
对于这个特殊的结构,您可以从
中获取您要查找的元素>>> 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']
当你说完了所有的事情,它可能看起来像这样:
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