Use json.loads()
method to load JSON files in Python. This method returns a dictionary. json.load() accepts file objects, parses the JSON data, and populates a Python dictionary.
json.load(file object)
Python JSON load file
A simple example code reads 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:
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 converting JSON objects into their respective Python objects.
JSON OBJECT | PYTHON OBJECT |
---|---|
object | dict |
array | list |
string | str |
null | None |
number (int) | int |
number (real) | float |
true | True |
false | False |
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.