簡體   English   中英

有人如何通過JSON文件中的嵌套數組在python中多行創建python key:value字典?

[英]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:“樹”]

[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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM