Convert Nested JSON Object to Dictionary
In this example, we will convert the nested JSON into a Python dictionary. For JSON data we will use the same JSON file used in the above example.
Python3
# importing the module import json # Opening JSON file with open ( 'data.json' ) as json_file: data = json.load(json_file) # for reading nested data [0] represents # the index value of the list print (data[ 'people1' ][ 0 ]) # for printing the key-value pair of # nested dictionary for loop can be used print ( "\nPrinting nested dictionary as a key-value pair\n" ) for i in data[ 'people1' ]: print ( "Name:" , i[ 'name' ]) print ( "Website:" , i[ 'website' ]) print ( "From:" , i[ 'from' ]) print () |
Output :
Convert JSON to dictionary in Python
JSON stands for JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called JSON. To use this feature, we import the Python JSON package into Python script. The text in JSON is done through quoted-string which contains a value in key-value mapping within { }. It is similar to the dictionary in Python.
Function Used
json.load(): json.load() function is present in Python built-in ‘JSON’ module. This function is used to parse the JSON string.
json.loads(): json.loads() function is present in Python built-in ‘json’ module. This function is used to parse the JSON string.