如何解析嵌套的json对象?

2024-06-16 15:02:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图加载一个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”中的嵌套对象,例如“person”、“kids”及其内容和“parents”


Tags: 文件对象namejson内容ageaswith
2条回答

加载JSON object的代码如下所示:

from json import loads, load

with open("file.json") as file:
    var = loads(load(file))
    # loads() transforms the string in a python dict object

下面使用递归函数的代码可以使用嵌套字典或“字典列表”中的特定键提取值:

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')

输出

[{'address': 'some place ave. 123', 'age': 47, 'name': 'Joe'}]

相关问题 更多 >