添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

如何解析嵌套的json对象?

1 人关注

我试图加载一个JSON文件来解析嵌套在根对象中的内容。目前我已经打开了JSON文件,并以这种方式加载。

with open(outputFile.name) as f:
        data = json.load(f)

为了回答这个问题,这里举例说明JSON文件的内容是怎样的。

"rootObject" : "person" : "address" : "some place ave. 123", "age" : 47, "name" : "Joe" "kids" : "age" : 20, "name" : "Joey", "studySubject":"math" "age" : 16, "name" : "Josephine", "studySubject":"chemistry" "parents" : "father" : "Joseph", "mother" : "Joette"

我如何访问 "rootObject "中的嵌套对象,如 "人"、"孩子 "及其内容和 "父母"?

3 个评论
data['rootObject']['person']['name'] and for kid in data['rootObject']['kids']:
一旦 json.load 返回一个Python值,你从JSON开始的事实就不再是真的相关了。 data 并不是JSON,它只是一个Python的 dict
啊,我明白了,非常感谢你。现在有了更多的意义
python
python-2.7
Fabrizo
Fabrizo
发布于 2021-06-02
2 个回答
perpetualstudent
perpetualstudent
发布于 2021-06-02
已采纳
0 人赞同

下面的代码使用递归函数可以 使用特定键提取数值 在一个嵌套的字典或 "字典的列表 "中。

data = {
"rootObject" : 
    "person" : 
        "address" : "some place ave. 123",
        "age" : 47,
        "name" : "Joe"
    "kids" : 
            "age" : 20,
            "name" : "Joey",
            "studySubject":"math"
            "age" : 16,
            "name" : "Josephine",
            "studySubject":"chemistry"
    "parents" : 
        "father" : "Joseph",
        "mother" : "Joette"
def get_vals(nested, key):
    result = []
    if isinstance(nested, list) and nested != []:   #non-empty list
        for lis in nested:
            result.extend(get_vals(lis, key))
    elif isinstance(nested, dict) and nested != {}:   #non-empty dict
        for val in nested.values():
            if isinstance(val, (list, dict)):   #(list or dict) in dict
                result.extend(get_vals(val, key))
        if key in nested.keys():   #key found in dict
            result.append(nested[key])
    return result
get_vals(data, 'person')

Output

[{'address': 'some place ave. 123', 'age': 47, 'name': 'Joe'}]
    
Rafael Setton
Rafael Setton
发布于 2021-06-02
0 人赞同

加载 JSON object 的代码应该是这样的。

from json import loads, load