I have a JSON file with values in [] brackets as shown. I am trying to create a [key:value] dictionary that shows the [id_value : text_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":[]}}

Taking as an example the first two JSON lines above. The output for the dictionary would be :


[6127465 : 'trees']

[9285628 : 'grass' , 'trees'] and so on.


Here is what I have coded so far but I can't get the values very well.

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

New edit. (Answer)

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
1

There are 1 answers

0
Biyinzika On BEST ANSWER

New edit : Answer

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