Softwares often use JSON file format to store and transmit data. While writing software in python, we might need to convert a JSON string or file into a python object. This article discusses how to load JSON into a python dictionary.
What is JSON Format?
JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write and for machines to parse and generate.
The syntax of JSON consists of keys and values, separated by a colon (:), and surrounded by curly braces ({}). The keys must be strings, and the values can be any data type including strings, numbers, arrays, and objects.
For example, the following JSON string contains data of an employee.
{
"employee": {
"name": "John Doe",
"age": 35,
"job": {
"title": "Software Engineer",
"department": "IT",
"years_of_experience": 10
},
"address": {
"street": "123 Main St.",
"city": "San Francisco",
"state": "CA",
"zip": 94102
}
}
}
Here,
- The name of the employee is “John Doe”.
- The age of the employee is 35.
- The job title of the employee is “Software Engineer”.
- The department the employee works in is “IT”.
- The employee has 10 years of experience in the field.
- The employee’s address includes street name “123 Main St.”, city “San Francisco”, state “CA”, and zip code 94102.
You can observe that the JSON format is almost similar to the format of a python dictionary.
Convert JSON String to Python Dictionary
To load a json string into a python dictionary, you can use the loads()
method defined in the json module. The loads()
method takes the JSON string as its input argument and returns the dictionary as shown below.
import json
json_string='{"name": {"first": "John", "last": "Doe"}, "address": {"street": "123 Main St", "city": "Anytown", "state": "CA", "zipcode": "12345"}, "email": "[email protected]", "age": 32}'
print("The JSON string is:")
print(json_string)
python_dict=json.loads(json_string)
print("The python dictionary is:")
print(python_dict)
Output:
The JSON string is:
{"name": {"first": "John", "last": "Doe"}, "address": {"street": "123 Main St", "city": "Anytown", "state": "CA", "zipcode": "12345"}, "email": "[email protected]", "age": 32}
The python dictionary is:
{'name': {'first': 'John', 'last': 'Doe'}, 'address': {'street': '123 Main St', 'city': 'Anytown', 'state': 'CA', 'zipcode': '12345'}, 'email': '[email protected]', 'age': 32}
While using the loads()
method, you should pass a valid JSON string as an input argument. Otherwise, the program will run into an error.
Instead of using the loads()
function, you can also use the JSONDecoder
class to convert a JSON string to python dictionary. The JSONDecoder
class is defined in the json module and has a decode()
method.
When the decode()
method is invoked on the JSONDecoder
object, it takes a json string as its input argument. After execution, it returns a dictionary as shown below.
import json
json_string='{"name": {"first": "John", "last": "Doe"}, "address": {"street": "123 Main St", "city": "Anytown", "state": "CA", "zipcode": "12345"}, "email": "[email protected]", "age": 32}'
print("The JSON string is:")
print(json_string)
python_dict=json.JSONDecoder().decode(json_string)
print("The python dictionary is:")
print(python_dict)
Output:
The JSON string is:
{"name": {"first": "John", "last": "Doe"}, "address": {"street": "123 Main St", "city": "Anytown", "state": "CA", "zipcode": "12345"}, "email": "[email protected]", "age": 32}
The python dictionary is:
{'name': {'first': 'John', 'last': 'Doe'}, 'address': {'street': '123 Main St', 'city': 'Anytown', 'state': 'CA', 'zipcode': '12345'}, 'email': '[email protected]', 'age': 32}
Suggested Reading: Working with JSON files in Python
Convert JSON File to Python Dictionary
If we have a JSON file instead of a json string, we can also convert it to a dictionary. For this, we will use the following steps.
- First, we will open the JSON file in read mode using the
open()
function. Theopen()
function takes the file name as its first input argument and the python literal “r” as its second input argument. After execution, it returns a file pointer. - Next, we will pass the file pointer to the
load()
method defined in the json module. Theload()
method will return the python dictionary after execution.
You can observe this in the following example.
import json
file=open("person_data.json","r")
python_dict=json.load(file)
print("The python dictionary is:")
print(python_dict)
Output:
The python dictionary is:
{'name': {'first': 'John', 'last': 'Doe'}, 'address': {'street': '123 Main St', 'city': 'Anytown', 'state': 'CA', 'zipcode': '12345'}, 'email': '[email protected]', 'age': 32}
Convert JSON to User-defined Python Objects
Instead of obtaining a dictionary, we can also convert a JSON file or string to a custom python object. For this, you can read this article on custom JSON decoder in python.
Conclusion
In this article, we have discussed how to load a json string or file to a dictionary. To learn more about python programming, you can read this article on how to convert JSON to YAML in Python. You might also like this article on custom json encoders in python.
I hope you enjoyed reading this article. Stay tuned for more informative articles.
Happy Learning!
Recommended Python Training
Course: Python 3 For Beginners
Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.