我有一个带有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)
。
答案 0 :(得分:1)
对于这个特定的结构,您可以从
获取您正在寻找的元素>>> 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