How to Read JSON file into Python dictionary?
This is quick guide for developers to read a json file into Python dictionary object. JSON is most proffered way of transferring data for web application. In a web application data from server can be sent to client in the JSON format. In this example we have we have a json file on the disk which we will read and then convert it to dictionary object. We will see the type of object created and then get values by providing the key to dictionary object.
I was working on a project which was using JSON files for settings. So, I investigated about the code to be used for reading JSON file in dictionary. I finally used the json.load() of json to read the content of json file as dictionary object.
Here is the content of 1.json:
{
"availability": "available",
"name": "Python Book",
"price": "100"
}
Following program is used read the data into Python dictionary:
import json
from pprint import pprint
with open('1.json') as f:
data = json.load(f)
pprint(data)
print(data["name"])
print(data["price"])
print(data["availability"])
If you run the program it gives following output:
Console output:
>>> import json
>>> from pprint import pprint
>>>
>>> with open('1.json') as f:
... data = json.load(f)
...
>>> pprint(data)
{'availability': 'available', 'name': 'Python Book', 'price': '100'}
>>>
>>> print(data["name"])
Python Book
>>>
>>> print(data["price"])
100
>>>
>>> print(data["availability"])
available
>>>
In this tutorial we learned to read json file data into dictionary object in Python. Python provides json.load() function for loading the data from a file into dictionary object. In the previous section we have learned How to save python dictionary object into JSON?
We have many tutorials on Python programming language for learning Python with ease. Check our Python Tutorials section.
Related Python tutorials: