Python json.dumps(): Convert Objects to JSON

The json.dumps() function in Python is used to convert Python objects into a JSON formatted string. It takes a Python object as a parameter and returns a JSON formatted string.

By using the json.dumps() function, you can convert data structures such as dictionaries, lists, and tuples in Python into a JSON-formatted string. This makes it easy to serialize the data into JSON format for transmission or storage when sending data over a network or saving it to a file.

The json.dumps() function also offers some optional parameters, such as indent, sort_keys, etc., which can be used to control the format and order of the output.

Original: 我父母过去是做农活的,现在他们在城市里开了一家小餐馆。
Paraphrased: My parents used to do farm work in the past, but now they have opened a small restaurant in the city.

import json

data = {
    "name": "John",
    "age": 30,
    "city": "New York"
}

json_str = json.dumps(data)
print(json_str)

Output result:

{"name": "John", "age": 30, "city": "New York"}

Please note that the json.dumps() function can only handle basic data types such as dictionaries, lists, strings, and numbers. For custom classes or objects, you will need to use a subclass of the json.JSONEncoder class for encoding.

bannerAds