Convert JSON to List of Dictionaries in Python : Methods

JSON stands for  JavaScript Object Notation. It is the plain text used for transmitting and storing data to make many applications on it. Python provides json.loads() function to convert the JSON to a list of dictionaries in python. In this tutorial, you will know examples of it.

Syntax of json.loads()

json.loads(your_file_object)

The function json.loads() accepts a file object and it returns the JSON object.

Sample of the JSON Data

For example 1 the JSON data is assigned to the variable as a string and for example 2 the JSON data is stored in the file named “data.json”

Convert JSON to a list of dictionaries in python Examples

Example 1: JSON object as a string

import json

json_string = """[
  {
    "country": "USD",
    "capital": "Washington DC",
    "dial_code": 1
  },
  {
    "name": "UK",
    "capital": "London",
    "dial_code": 44
  }
]"""

dict_list = json.loads(json_string)

print(dict_list)
print(type(dict_list))

Output

[{'country': 'USD', 'capital': 'Washington DC', 'dial_code': 1}, {'name': 'UK', 'capital': 'London', 'dial_code': 44}]
<class 'list'>

Here JSON object is a string and it contains a list of dictionaries. To convert it to a list of dictionaries then pass the JSON object as an argument for the json.loads() function.

Example 2: JSON object in a file

data.json file

[
  {
    "country": "USD",
    "capital": "Washington DC",
    "dial_code": 1
  },
  {
    "name": "UK",
    "capital": "London",
    "dial_code": 44
  }
]

Full Code

import json
with open("data.json") as f:
  data = json.loads(f)
print(data)
print(type(data))

Output

[{'country': 'USD', 'capital': 'Washington DC', 'dial_code': 1}, {'name': 'UK', 'capital': 'London', 'dial_code': 44}]
<class 'list'>

In this example, you are reading the JSON object from a file ( data.json) and passing it to the json.loads() as an argument.

Summary

In this tutorial, you have known the syntax of the json.loads() function. Then you have learned how to convert JSON objects to a list of dictionaries when the JSON object is a string (Example 1 ). After that, you learned how to read JSON file and convert it to a list of dictionaries.

Hi, I am CodeTheBest. Here you will learn the best coding tutorials on the latest technologies like a flutter, react js, python, Julia, and many more in a single place.

SPECIAL OFFER!

This Offer is Limited! Grab your Discount!
15000 ChatGPT Prompts
Offer Expires In:
close-link