Convert Text to JSON in Python – Python Tutorial

By | August 11, 2021

When we are crawling a web page, we may get a json string. However, how to convert this string (text) to json object in python? In this tutorial, we will introduce you how to do.

How to convert text to json in python?

We can use json.loads() function.

For example:

import json

js = '''{
        "id": "123321233",
        "audio": {"aid": "aaa", "bits": 16, "chnl": 1, "encoding": 1, "offset": 0, "rate": 8000, "spnk": 1
        }
    }'''

data = json.loads(js)
print(type(data))
print(data)

Run this code, we will get:

<class 'dict'>
{'id': '123321233', 'audio': {'aid': 'aaa', 'bits': 16, 'chnl': 1, 'encoding': 1, 'offset': 0, 'rate': 8000, 'spnk': 1}}

We can find:

  • json.loads() can convert a json string to python dictionary object
  • We can operate a json object by python dictionary

Leave a Reply