有人如何从 JSON 文件中的嵌套数组创建 python key:value 字典,在 python 中包含多行?
How can someone create a python key:value dictionary from a nested array in a JSON file with multiple lines in python?
我有一个 JSON 文件,其值在 [] 括号中,如图所示。我正在尝试创建一个显示 [id_value : text_value.]
的 [key:value] 字典
{"id":6127465, "users":{"name":[{"dr_info":[28,37],"text":"trees"}],"favorites":[]}}
{"id":9285628, "users":{"name":[{"dr_info":[16,24],"text":"grass"}, {"id_info":[30,34],"text":"trees"}],"favorites":[]}}
{"id":7625927, "users":{"name":[{"dr_info":[18,23],"text":"grass"}],"favorites":[], "type" : "photo"}}
{"id":8725946, "users":{"name":[{"dr_info":[23,33],"text":"grass"}, {"id_info":[37,41],"text":"trees"}],"favorites":[]}}
以上面前两行JSON为例。字典的输出为:
[6127465 : 'trees']
[9285628 : 'grass' , 'trees'] 等等。
这是我目前编写的代码,但我无法很好地获得这些值。
dict={}
with open(fileName, 'r') as file_to_read:
for line in file_to_read:
data = json.loads(line)
json_tree = objectpath.Tree(data)
json.dumps(data, ensure_ascii=True)
dict[json_tree.execute('$.id')] = json_tree.execute('$.users.name.text')
return dict
新编辑。 (答案)
dict={}
with open(fileName, 'r') as file_to_read:
for line in file_to_read:
data = json.loads(line)
json_tree = objectpath.Tree(data)
json.dumps(data)
dict[json_tree.execute('$.id')] = list(json_tree.execute('$.users.name.text'))
return dict
新编辑:回答
dict={}
with open(fileName, 'r') as file_to_read:
for line in file_to_read:
data = json.loads(line)
json_tree = objectpath.Tree(data)
json.dumps(data)
dict[json_tree.execute('$.id')] = list(json_tree.execute('$.users.name.text'))
return dict
我有一个 JSON 文件,其值在 [] 括号中,如图所示。我正在尝试创建一个显示 [id_value : text_value.]
的 [key:value] 字典{"id":6127465, "users":{"name":[{"dr_info":[28,37],"text":"trees"}],"favorites":[]}}
{"id":9285628, "users":{"name":[{"dr_info":[16,24],"text":"grass"}, {"id_info":[30,34],"text":"trees"}],"favorites":[]}}
{"id":7625927, "users":{"name":[{"dr_info":[18,23],"text":"grass"}],"favorites":[], "type" : "photo"}}
{"id":8725946, "users":{"name":[{"dr_info":[23,33],"text":"grass"}, {"id_info":[37,41],"text":"trees"}],"favorites":[]}}
以上面前两行JSON为例。字典的输出为:
[6127465 : 'trees']
[9285628 : 'grass' , 'trees'] 等等。
这是我目前编写的代码,但我无法很好地获得这些值。
dict={}
with open(fileName, 'r') as file_to_read:
for line in file_to_read:
data = json.loads(line)
json_tree = objectpath.Tree(data)
json.dumps(data, ensure_ascii=True)
dict[json_tree.execute('$.id')] = json_tree.execute('$.users.name.text')
return dict
新编辑。 (答案)
dict={}
with open(fileName, 'r') as file_to_read:
for line in file_to_read:
data = json.loads(line)
json_tree = objectpath.Tree(data)
json.dumps(data)
dict[json_tree.execute('$.id')] = list(json_tree.execute('$.users.name.text'))
return dict
新编辑:回答
dict={}
with open(fileName, 'r') as file_to_read:
for line in file_to_read:
data = json.loads(line)
json_tree = objectpath.Tree(data)
json.dumps(data)
dict[json_tree.execute('$.id')] = list(json_tree.execute('$.users.name.text'))
return dict