Search code examples
pythonjsondictionaryobjectpath

How can one create a python dictionary (key : value) from select objects in a JSON file with multiple JSON lines


I have a file with multiple JSON lines as shown below.

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

My desired output should show only the ID number and the "Grass is green" as a [key : value] pair as in dictionaries in Python :

563221 : "Grass is green"

612835 : "Textual blue"

I am currently using ObjectPath to query. Using the tuples, I can output all the data but I can't select sections of the data. Below is the code that I am using.

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

Solution

  • You should use the json library to translate each line of the file to json then easily extract the data you need.

    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) converts the string in json_string to json.