PythonExamples

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}]

Examples

1. Convert JSON Object to Python 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'])

Output

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

2. Convert JSON nested object to Python 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'])

Output

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

Summary

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


Python Libraries