Convert String to JSON Object using Python

In this tutorial, we will understand the concepts of JSON. And learn different methods to Convert String to a JSON object in Python.

Example of a JSON Object

{  
    "employee": {  
        "name":       "Tushar",   
        "salary":      78000,   
        "married":     true  
    }  
}

Convert String to JSON Object in Python

In most web APIs, data which transmitted and received are generally in the form of a string of dictionary. To use this data to extract meaningful information we need to convert that data in the dictionary form so that we can use it for further operations. Python has a built-in module “json”, which has various methods to serialize and deserialize JSON.

There are two ways to convert string to JSON object:-

  • using json.load
  • using eval

Method 1

The below code demonstrates the use of json.loads to convert string to json object.

import json 
   
initial_string = {'shreeraj': 12, 'shalu' : 62,  'jennifer' : 98, 'elson' : 55} 
  
initial_string = json.dumps(initial_string) 
print ("initial_string - ", initial_string) 
print ("type of initial_string", type(initial_string)) 
  
result = json.loads(initial_string) 
   
print ("result - ", str(result)) 
print ("type of result", type(result))

Output:-

initial_string -  {'shreeraj': 12, 'shalu' : 62,  'jennifer' : 98, 'elson' : 55}
type of initial_string <class 'str'>
result -  {"shalu": 62, "elson": 55, "shreeraj": 12, "jennifer": 98}
type of result <class 'dict'>

In the above code, we first initialize the json object. Then print the content and the type of the json object. The string is then converted to json using the function json.loads. Then finally we print the result of the conversion and its type.

Method 2

The below demonstrates the use of the function eval()

# inititialising json object string 
initial_string = """{'shreeraj': 12, 'shalu' : 62, 'jennifer' : 98, 'elson' : 55}"""
  
# printing initial json 
print ("initial_string - ", initial_string) 
print ("type of initial_string", type(initial_string)) 
  
# converting string to json 
result = eval(initial_string) 
  
# printing final result 
print ("result - ", str(result)) 
print ("type of result", type(result))

Output:-

initial_string - {'shreeraj': 12, 'shalu' : 62, 'jennifer' : 98, 'elson' : 55}
type of initial_string <class 'str'>
result - {'jennifer': 98, 'shalu': 62, 'shreeraj': 12, 'elson': 55}
type of result <class 'dict'>

Thank you for reading the tutorial. I hope it helps you.

You may also check:-
Append to JSON file in Python.
How to merge two JSON files in Python.

Leave a Reply

Your email address will not be published. Required fields are marked *