我有一个包含多个JSON行的文件,如下所示。

{"status str":null,"id":563221, "filter":"low","text" : "Grass is green"}
{"status str":null,"id":612835, "filter":"high","text" : "Textual blue"}


我想要的输出应该只显示ID号,并且“ Grass is green”作为[key:value]对显示,就像Python中的字典一样:

563221:“草是绿色的”

612835:“文字蓝”

我目前正在使用ObjectPath进行查询。使用元组,我可以输出所有数据,但不能选择数据的各个部分。下面是我正在使用的代码。

read_data = []
with open(fileName, 'r') as file_to_read:
    for line in filetoread:
        json_tree = objectpath.Tree(read_data)
        dict = {tuple(json_tree.execute('$.id')) : tuple(json_tree.execute('$.text'))}
        line = next(filetoread)
return dict

最佳答案

您应该使用json库将文件的每一行转换为json,然后轻松提取所需的数据。

import json

dict = {}
with open(fileName, 'r') as file_to_read:
    for line in filetoread:
        json_line = json.loads(line)
        dict[json_line['id']] = json_line['text']
return dict


json.loads(json_string)将json_string中的字符串转换为json。

关于python - 如何使用多个JSON行从JSON文件中的选择对象创建python字典(键:值),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52481557/

10-08 22:13
查看更多