DEV Community

Tommi k Vincent
Tommi k Vincent

Posted on

Reading JSON file in Python

Suppose, you have a file namedperson.json which contains a JSON object.

{"name": "Vincent", 
"languages": ["English", "Swahili"]
}
Enter fullscreen mode Exit fullscreen mode

Here is how you can read the file using python:

import json 

with open('person.json','r')  as file:
    data  = json.load(file)

    print(data)

Enter fullscreen mode Exit fullscreen mode

We start by importing the json module, which provides functions for working with JSON data and then with open('person.json', 'r') as file: statement opens the JSON file called 'person.json' in read mode. The with statement ensures that the file is properly closed after we finish using it, even if an exception occurs.
json.load() function is used to load the contents of the JSON file into a Python data structure. The json.load() function takes a file object as input and returns the deserialized JSON data. In this case, the returned data is assigned to the variable data.
print(data) displays the contents of the JSON file, showing the structure and values as a Python data structure.

output: {'name': 'Vincent', 'languages': ['English', 'Swahili']}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)