How to Parse a JSON File in Python?

Estimated read time 1 min read

To parse a JSON file in Python, you can use the json module that comes built-in with Python. Here’s an example:

Suppose you have a file named data.json with the following contents:

{
    "name": "John",
    "age": 30,
    "city": "New York"
}

You can parse this JSON file in Python as follows:

import json

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

print(data)

This code opens the data.json file using the open() function, reads the contents of the file and loads it into a Python dictionary using the json.load() method. The resulting dictionary is stored in the data variable, which is then printed using the print() function.

The output of the above code should be:

{'name': 'John', 'age': 30, 'city': 'New York'}

Now you can access the values of the keys in the JSON file as you would with a regular dictionary, for example:

print(data['name'])  # Output: 'John'
print(data['age'])   # Output: 30
print(data['city'])  # Output: 'New York'

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply