How to read JSON files in Python

Asked 2 years ago, Updated 2 years ago, 134 views

I made a code to read the entire Json file with Python It won't go back

And I don't read the entire file I want to use each of them What should I do?

{
    "maps": [
        {
            "id": "blabla",
            "iscategorical": "0"
        },
        {
            "id": "blabla",
            "iscategorical": "0"
        }
    ],
    "masks": [
        "id": "valore"
    ],
    "om_points": "value",
    "parameters": [
        "id": "valore"
    ]
}
json_data=open(file_directory).read()

data = json.loads(json_data)
pprint(data)

json python parsing

2022-09-21 18:11

1 Answers

First of all, the reason the code doesn't work is because the json file is wrong. You wrote [] where you should write {}. {} is dictionary and [] is a list

{
 "maps":[
         {"id":"blabla","iscategorical":"0"},
         {"id":"blabla","iscategorical":"0"}
        ],
"masks":
         {"id":"valore"},
"om_points":"value",
"parameters":
         {"id":"valore"}
}

If you do this, with the code you wrote, You'll be able to read the entire file.

And to read the values one by one, Write the Python code as follows

import json
from pprint import pprint

with open('data.json') as data_file:    
    data = json.load(data_file)

pprint(data) #data stores the entire json in dictionary form

#--- Same up to here-----

data["maps"][0]["id"] #Access values one by one
data["masks"]["id"]
data["om_points"]


2022-09-21 18:11

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.