Python JSON to Dictionary

Python JSON to Dictionary

Python JSON to Dictionary

To convert Python JSON string to Dictionary, use json.loads() function. Note that only if the JSON content is a JSON Object, and when parsed using loads() function, we get Python Dictionary object.

JSON content with array of objects will be converted to a Python list by loads() function.

For example, following JSON content will be parsed to a Python Dictionary.

{"a":54, "b": 28}

Following JSON content will be parsed to a Python List.

[{"a": 54, "b":28}, {"c": 87, "d":16}, {"e": 53, "f":74}]

Example 1: JSON Object to Dictionary

In this example, we will take a JSON string that contains a JSON object. We will use loads() function to load the JSON string into a Python Dictionary, and access the name:value pairs.

Python Program

import json

jsonString = '{"a":54, "b": 28}'
aDict = json.loads(jsonString)
print(aDict)
print(aDict['a'])
print(aDict['b'])
Run this program ONLINE

Output

{'a': 54, 'b': 28}
54
28

Example 2: JSON Nested Object to Dictionary

In this example, we will take a JSON string that contains a JSON object nested with another JSON object as value for one of the name:value pair. We will parse the JSON object to Dictionary, and access its values.

Python Program

import json

jsonString = '{"a":54, "b": {"c":87}}'
aDict = json.loads(jsonString)
print(aDict)
print(aDict['a'])
print(aDict['b'])
print(aDict['b']['c'])
Run this program ONLINE

Output

{'a': 54, 'b': {'c': 87}}
54
{'c': 87}
87

Summary

In this tutorial of Python Examples, we learned how to convert a JSON Object string to a Python Dictionary, with the help of well detailed example programs.