Skip to content

Python JSON to string | Example code

  • by

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:

Python JSON to string

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:

Convert Json to String with API

Supports the following objects and types by default:

PythonJSON
dictobject
list, tuplearray
str, Unicodestring
int, long, floatnumber
Truetrue
Falsefalse
Nonenull

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.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading