In our previous Python tutorial, you have learned how to convert string into bytes in Python. In this tutorial, you will learn how to convert String data to JSON object in Python.
While getting string data from web API’s, we need to convert that string data into JSON object or dictionary. Python provides build-in JSON package with method json.loads()
to converting Strings data to JSON.
So let’s proceed with coding:
Convert String to JSON
We can easily convert String data to JSON using json.loads()
method.
In below example code, we are importing json
package. We have employee string data and converting that data into json object using json.loads()
method.
import json employee = ''' { "employee": [ { "empid": 1, "name": "Jhon William", "age": 25, "address": "Newyork" }, { "empid": 2, "name": "Adam Gill", "age": 35, "address": "London" } ] } ''' print(employee) print("The type of object is: ", type(employee)) empObj = json.loads(employee) print(empObj) print("The type of object is: ", type(empObj))
In above code, we have converted string data employee
into json obejct empObj
using json.loads(employee)
method. We have also printed data object and type. Below is the output of above exmaple code:
{ "employee": [ { "empid": 1, "name": "Jhon William", "age": 25, "address": "Newyork" }, { "empid": 2, "name": "Adam Gill", "age": 35, "address": "London" } ] } The type of object is:{'employee': [{'empid': 1, 'name': 'Jhon William', 'age': 25, 'address': 'Newyork'}, {'empid': 2, 'name': 'Adam Gill', 'age': 35, 'address': 'London'}]} The type of object is: