Python supports JSON through a built-in package called json. To use this package we need to import json. load() and loads() methods are used to read the json.
load() Method: Json load() method accepts file object and converts into a dict in python.
Input json file: sample.json
{
"name":"chakradhar",
"age":28,
"emp_details":[
{
"office":"infoblox",
"location":"banglore"
}
]
}
Program:
>>> import json
>>> with open("sample.json","r") as file:
... data = json.load(file)
...
>>> data
{'name': 'chakradhar', 'age': 28, 'emp_details': [{'office': 'infoblox', 'location': 'banglore'}]}
>>> type(data)
<class 'dict'>
As mentioned above json is converted into a python dictionary
loads() Method: Json loads() method accept json string and convert into dict in python.
Program:
>>> import json
>>> details = '{"name":"chakradhar","age":28}'
>>> data = json.load(details)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/json/__init__.py", line 293, in load
return loads(fp.read(),
AttributeError: 'str' object has no attribute 'read'
>>> data = json.loads(details)
>>> data
{'name': 'chakradhar', 'age': 28}
>>> type(data)
<class 'dict'>
In the above, we tried to use load() method, It raised an error because load() method accepts only file object not a string. For json string we used loads() methods. Will see another example using files.
>>> with open("sample.json", "r") as file:
... data = json.loads(file.read())
...
>>> data
{'name': 'chakradhar', 'age': 28, 'emp_details': [{'office': 'infoblox', 'location': 'banglore'}]}
>>> type(data)
<class 'dict'>