python - 有人如何从 JSON 文件中的嵌套数组创建 python 键:值字典,在 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:'树']
[9285628:'草','树']等等。
这是我到目前为止编写的代码,但我无法很好地获得这些值。
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
推荐阅读
- java - 如何合并输入和输出音频以发送另一个会议者
- javascript - 从jQuery中的数组填充复选框和标签属性
- ios - 如何修复 ios 10 中的崩溃“数据 <> 不代表有效的 UUID”?
- c# - 包含 ippiFFTGetSize_C_32fc ().(intel IPP) 创建的 dll 文件中 System.DllNotFoundException 的问题
- java - 如何使用spring boot连接到oracle数据库
- apache-kafka - 如何从 android /iOS 设备检索到 Kafka 生产者 API Spark 流
- bash - #+ 在 bash 脚本中是什么意思?
- hadoop - 这些“抢占”的 Yarn 命令有什么作用?
- kendo-ui-angular2 - 如何以编程方式设置对话框标题内容
- mysql - 使用 LIKE 和 CONCAT 的 MySQL/ORACLE 性能