AppDividend
Latest Code Tutorials

How to Convert Python String to JSON Object

0

Python provides an inbuilt json package which has various methods to serialize and deserialize JSON. Sending 

Convert Python String to JSON

To convert a  Python string to JSON, use the json.loads() function. The json.loads() function is used to parse valid JSON String into Python dictionary. The loads() method accepts a valid json string and returns a dictionary to access all items.

To make use of this method, we have to import the json package offered by Python. The process of converting json data to python objects called deserialization.

# app.py

import json

json_string = '''
{
  "students": [
    {
      "name": "Millie Brown",
      "active": true,
      "rollno": 11
    },
    {
      "name": "Sadie Sink",
      "active": true,
      "rollno": 10
    }
  ]
}
'''
print(json_string)
print("The type of object is: ", type(json_string))
stud_obj = json.loads(json_string)
print(stud_obj)
print("The type of object is: ", type(stud_obj))
json_obj = json.dumps(stud_obj)
print(json_obj)
print("The type of object is: ", type(json_obj))

Output

{
  "students": [
    {
      "name": "Millie Brown",
      "active": true,
      "rollno": 11
    },
    {
      "name": "Sadie Sink",
      "active": true,
      "rollno": 10
    }
  ]
}

The type of object is:  <class 'str'>
{'students': [{'name': 'Millie Brown', 'active': True, 'rollno': 11}, 
              {'name': 'Sadie Sink', 'active': True, 'rollno': 10}]}
The type of object is:  <class 'dict'>
{"students": [{"name": "Millie Brown", "active": true, "rollno": 11}, 
              {"name": "Sadie Sink", "active": true, "rollno": 10}]}
The type of object is:  <class 'str'>

In this example, first, we are converting the json string to the Python dictionary object using json.loads() method and then converting the dictionary to string using json.dumps() method.

Data Conversion from JSON to Python Objects

  1. object => dict
  2. array => list
  3. string => str
  4. number (int) => int
  5. number (real) => float
  6. true => True
  7. false => False
  8. null => None

Conclusion

If we have a JSON string or JSON data, we can easily parse it using the json.loads() method found in the json package.

See also

How to create a json file in Python

How to read json file in Python

Python json to dictionary

Python json to csv

Python json parse

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.