python

Convert JSON string to Python collections - like list, dictionaries

You can convert a JSON string to python collections like lists, dictionaries using json.loads() method in python. You need to import json module first to use it.

import json

#Convert object to python dict
json_str = '{"id": 1, "name": "Suman Kumar", "city": "Delhi"}'
my_dict = json.loads(json_str)
print(my_dict["id"])
print(my_dict["name"])
print(my_dict["city"])
# -> 1
# -> Suman Kumar
# -> Delhi

#Convert to python list of dictionaries
json_str = """[
  {"id": 1, "name": "Suman Kumar"},
  {"id": 2, "name": "Gaurav"},
  {"id": 3, "name": "John"}
]"""
my_list = json.loads(json_str)
print(my_list[1])
# -> prints {'id': 2, 'name': 'Gaurav'}

To import json module in python use the below syntax

import json

json.loads() method in python

To convert a JSON string to python collection we use json.loads() method. It takes one required parameter that needs to be converted to python dict or python list.

Basic Syntax:

json.loads(json_string)

Example 1 - Convert String to Python Dictionary

In this example, we have a JSON string json_str and we are converting it to Python Dictionary and getting values based on dictionary keys.

The code example can be found below

import json

json_str = '{"subject": "Math", "code": "math-001"}'
my_dict = json.loads(json_str)
print(my_dict['subject'])
print(my_dict['code'])

Output

Math
math-001

Example 2 - Convert String to Python List

You can convert JSON array string to python list using json.loads() method. This will take JSON string as the input parameter and returns the python list.

The code example can be found below

import json

json_str = '["One", "Two", "Three", "Four"]'
my_list = json.loads(json_str)
print(my_list[0])
print(my_list[2])

Output

One
Three

Example 3 - Convert String to Python List of Dictionaries

If you have a JSON string that consists an array of objects and want to convert it to Python List of Dictionaries then you can use the below code.

import json

json_str = """[
  {"id": 1, "name": "Apple"},
  {"id": 2, "name": "Orange"},
  {"id": 3, "name": "Banana"}
]"""

list_of_dict = json.loads(json_str)

print(list_of_dict[1]["name"])
print(list_of_dict[2]["name"])

Output

Orange
Banana
Was this helpful?