我有一个大文件,每行都包含有效的嵌套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的核心中,所以我不知道如何解码它!在
Data
是一个有效的^{JSON
包含四个基本元素:{}
定义[]
定义Unicode
字符或公共backslash escapes
使用^{
string
转换为pythonobject
。这意味着每个内部JSON
元素都将表示为pythonobject
。在因此:
jfile.get('Study')
->;python list
要检索
Field
,您应该遍历研究列表:相关问题 更多 >
编程相关推荐