In this Python tutorial we will see how to convert a string to JSON. Python has a built in module “json”, which has various methods to serialize and deserialize JSON. To convert a string to JSON, we will be using the function loads(). Function loads() takes the input string and returns an object. Lets jump into more details using an example.

Python – Convert String To JSON – Example

Let us first look at the changes that happens to data types while converting a string into JSON. In the below example, we are converting a JSON string and its type is converted to dictionary. If the given string has an array, then Python will convert that into type list.

import json
json_string = '''
{
  "employees": [
    {
      "name": "John Watson",
      "dateOfJoin": "01/01/2018",
      "active": true,
      "awards": null
    },
    {
      "name": "William Ben",
      "dateOfJoin": "01/01/2015",
      "active": false,
      "awards": 1
    }
  ]
}
'''
employees_obj = json.loads(json_string)
print(type(employees_obj))
#Print JSON Object
print("_______________Print Converted JSON_____________________")
print(employees_obj)

Output:

<class 'dict'>
_______________Print Converted JSON_____________________
{'employees': [{'name': 'John Watson', 'dateOfJoin': '01/01/2018', 'active': True, 'awards': None}, {'name': 'William Ben', 'dateOfJoin': '01/01/2015', 'active': False, 'awards': 1}]}

Look at the output, boolean value is changed from “true” to “True”, null is changed to None. Below is the standard conversion that happens to datatypes while converting from string to JSON object in Python.

Data Conversion
  • object => dict
  • array => list
  • string => str
  • number (int) => int
  • number (real) => float
  • true => True
  • false => False
  • null => None

Extract Data After Conversion

Now that we have seen how to convert a string to JSON, let us take a look at how to access each elements in the object. In the below example code, we are using a for loop to iterate trough the list and print the name of each employee.

employees_obj = json.loads(json_string)
#Get the list of employees
employees = employees_obj["employees"]
print("\n_______________Employee List_____________________")
print(employees)
print("\n_______________Print Employee Name_____________________")
for employee in employees:
    print("Name => " , employee["name"])

Output:

_______________Employee List_____________________
[{'name': 'John Watson', 'dateOfJoin': '01/01/2018', 'active': True, 'awards': None}, {'name': 'William Ben', 'dateOfJoin': '01/01/2015', 'active': False, 'awards': 1}]

_______________Print Employee Name_____________________
Name =>  John Watson
Name =>  William Ben

 

Python Convert String To JSON
Tagged on: