Python - How To Iterate Through JSON Object in Python

ID : 232

viewed : 92

Tags : PythonPython JSON

vote vote

97

JSON (JavaScript Object Notation) is a popular data format to store and exchange data.

This tutorial will discuss the method to iterate through a JSON object in Python.

Use json.loads() With the Help of the for Loop to Iterate Through a JSON Object in Python

A built-in package, json, is provided by Python, which can be imported to work with JSON form data. In Python, JSON exists as a string or stored in a JSON object.

We use json.loads(str) to parse the string to a dictionary. Furthermore, we use the for loop for the process of iteration through the dictionary.

The following code implements the json.loads() function and the loop to iterate through a JSON object.

import json jsonstring1 = '{"k1": "v1", "k2": "v2"}'  #Load JSON string into a dictionary json_dicti = json.loads(jsonstring1)  #Loop along dictionary keys for key in json_dicti:     print(key, ":", json_dicti[key])  

Output:

k1 : v1 k2 : v2 

Note that a python dictionary is returned when the json.loads() command is executed, not a JSON object.

If it is a file that contains the JSON object, the json.load() function can be used to read the file. The following code uses the json.load() function to parse the file containing the JSON object.

Suppose the file named man.json contains this data.

{"fullname": "Tom",  "languages": ["English", "German"] } 

The code to parse this file is below.

import json  with open('man.json') as a:     dict1 = json.load(a) print(dict1) 

Output:

{'fullname': 'Tom', 'languages': ['English', 'German']} 

The open() function is used here to read the JSON file. Here also, we get a dictionary, dict1. After that, the process of iteration can be done on the dictionary.

  • Related HOW TO?