Google News
logo
Convert Python objects into JSON strings
To convert Python objects into JSON strings, you can use the `json` module which is included in the standard library in Python. This module provides two methods `dumps()` and `dump()` for converting Python objects into JSON strings.
Program :
import json

# create a dictionary
person = {
    "name": "John",
    "age": 30,
    "city": "New York"
}

# convert dictionary to JSON string using dumps()
json_string = json.dumps(person)

# print JSON string
print(json_string)
Output :
{"name": "John", "age": 30, "city": "New York"}
In the above example, we imported the `json` module and created a dictionary called `person`.

We then used the `dumps()` method of the `json` module to convert the dictionary into a JSON string and stored it in a variable called `json_string`.