0

我有一个 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)

4

1 回答 1

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
于 2013-06-12T13:30:59.793 回答