Skip to content

Python JSON load file

  • by

Use json.loads() method to load JSON files in Python. This method returns a dictionary. json.load() accepts file object, parses the JSON data, and populates a Python dictionary.

json.load(file object)

Python JSON load file

Simple example code read the content of this file. Below is the implementation.

You need to import the module before you can use it.

data.json

{
"emp": [
{
"name": "John",
"subject": "Data structures",
"Articles": 2
},
{
"name": "Mike",
"subject": "Algorithms",
"Articles": 10
},
{
"name": "Rohit",
"subject": "NAN",
"Articles": 8
}
]
}

main.py

import json

# Opening JSON file
f = open('modules/data.json')

# returns JSON object as a dictionary
data = json.load(f)

# Iterating through the json list
for i in data['emp']:
    print(i)

# Closing file
f.close()

Output:

Python JSON load file

Suppose, you have a file named person.json that contains a JSON object.


{"name": "Bob", 
"languages": ["English", "French"]
}

Here’s how you can parse this file:


import json

with open('path_to_file/person.json', 'r') as f:
  data = json.load(f)

# Output: {'name': 'Bob', 'languages': ['English', 'French']}
print(data)

Deserialization of JSON

The Deserialization of JSON means the conversion of JSON objects into their respective Python objects.

JSON OBJECTPYTHON OBJECT
objectdict
arraylist
stringstr
nullNone
number (int)int
number (real)float
trueTrue
falseFalse

Do comment if you have any doubts or suggestions on this Python JSON topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading