Using json.dumps() can convert JSON to string in Python. It would always produce a valid JSON string (assuming everything inside the object is serializable).
Python JSON to string example
Simple example code dumps() would convert None into null making a valid JSON string that can be loaded:
import json
json_obj = {"name": "John", "Age": 10, "DOB": None}
res = json.dumps(json_obj)
print(res)
print(type(res))
Output:
Another example
Convert Json to String with API using requests and json.dumps() method.
import json
import requests
# API
res = requests.get("https://reqres.in/api/products/3")
# Convert data to dict
data = json.loads(res.text)
# Convert dict to string
data = json.dumps(data)
print(data)
Output:
Supports the following objects and types by default:
Python | JSON |
---|---|
dict | object |
list, tuple | array |
str, Unicode | string |
int, long, float | number |
True | true |
False | false |
None | null |
Do comment if you have any doubts or suggestions on this Python JSON topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.