Python comes with a built-in module called json; pip is not required to instal it. JSON may be parsed from strings or files using the json library. The library converts JSON into a Python list or dictionary. Additionally, it can transform lists or dictionaries in Python into JSON strings.
Here is a Python program that demonstrates how to convert a Python object to JSON data using the json module:
import json
# Define a Python object
data = {
"name": "Peter John",
"age": 31,
"address": {
"street": "10 Main St",
"city": "Baltimore",
"state": "MD",
"zip": 21210
},
"phoneNumbers": [
{"type": "home", "number": "910-888-1234"},
{"type": "fax", "number": "61046-555-1234"}
]
}
# Convert the Python object to JSON data
json_data = json.dumps(data, indent=4)
# Print the JSON data
print(json_data)
ResultĀ
{
"name": "Peter John",
"age": 31,
"address": {
"street": "10 Main St",
"city": "Baltimore",
"state": "MD",
"zip": 21210
},
"phoneNumbers": [
{
"type": "home",
"number": "910-888-1234"
},
{
"type": "fax",
"number": "61046-555-1234"
}
]
}
Lets check the data type of the raw data [data] and the converted data [json_data]
print(type(data))
<class 'dict'>
print(type(json_data))
<class 'str'>
The json.dumps() function is used to convert the Python object to JSON data. The indent parameter is used to make the output more readable by adding indentation.
Additionally, you can also use json.dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw) to write JSON data to a file
The json.dump() method is used to write JSON data to a file-like object. It can take additional parameters such as indent, separators and sort_keys, etc.