.get方法对于嵌套的json没有

2024-10-03 11:26:32 发布

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

我有一个大文件,每行都包含有效的嵌套json,每个json看起来都像(实际数据要大得多,因此json的这种和平性仅作为说明):

       {"location":{"town":"Rome","groupe":"Advanced",
            "school":{"SchoolGroupe":"TrowMet", "SchoolName":"VeronM"}},
            "id":"145",
            "Mother":{"MotherName":"Helen","MotherAge":"46"},"NGlobalNote":2,
            "Father":{"FatherName":"Peter","FatherAge":"51"},
             "Study":[{
            "Teacher":["MrCrock","MrDaniel"],
           "Field":{"Master1":["Marketing", "Politics", "Philosophy"], 
           "Master2":["Economics", "Management"], "ExamCode": "1256"}
             }],
             "season":["summer","spring"]}

我需要解析这个文件,以便从每个json中只提取一些键值,以获得如下所示的dataframe:

^{pr2}$

我使用method proposed me in the other question.get,但它不适用于嵌套的json,因此,如果我尝试:

def extract_data(data):
    """ convert 1 json dict to records for import"""
    dummy = {}
    jfile = json.loads(data.strip())
    return (
    jfile.get('Study', dummy).get('Field', np.nan).get('Master1',np.nan),
    jfile.get('location', dummy).get('groupe', np.nan))

对于这行jfile.get('Study', dummy).get('Field', np.nan).get('Master1', np.nan),它向我抛出一个错误:

AttributeError: 'list' object has no attribute 'get'

显然,这是因为"Study"的值不是字典,也不是列表,而是一个有效的json!我该如何处理这个问题?是否存在类似.get的方法,但对于json?我想还有另一个选择:解码这个json,然后用.get解析它,但是问题是它在另一个json的核心中,所以我不知道如何解码它!在


Tags: 文件数据jsonfielddatagetnplocation
1条回答
网友
1楼 · 发布于 2024-10-03 11:26:32

Data是一个有效的^{}格式的字符串。JSON包含四个基本元素:

  • 对象:用大括号{}定义
  • 数组:用大括号[]定义
  • :可以是字符串、一个数字、一个对象、一个数组文本truefalsenull
  • 字符串:由双引号定义并包含Unicode字符或公共backslash escapes


使用^{}将递归地将string转换为python object。这意味着每个内部JSON元素都将表示为pythonobject。在

因此: jfile.get('Study')->;python list


要检索Field,您应该遍历研究列表:

file = json.loads(data.strip())
study_list = jfile.get('Study', [])  # don't set default value with different type 
for item in study_list:
  print item.get('Field')

相关问题 更多 >