json.dumps()
Lesson 4 of 9 in Coddy's Python JSON course.
The json.dumps() function is a key component of Python's json module. It converts (serializes) a Python object into a JSON-formatted string.
Basic Usage
Here's the basic syntax of json.dumps():
import json
json_string = json.dumps(python_object)
The function takes a Python object (like a dictionary or a list) as input and returns a JSON-formatted string.
Example
Let's convert a Python dictionary to a JSON string:
import json
python_dict = {
"name": "John",
"age": 30,
"city": "New York"
}
json_string = json.dumps(python_dict)
print(json_string)
# Output: {"name": "John", "age": 30, "city": "New York"}
Data Type Conversion
json.dumps() automatically handles the conversion of Python data types to their JSON equivalents:
- Python dictionaries become JSON objects
- Python lists become JSON arrays
- Python strings become JSON strings
- Python int and float become JSON numbers
- Python True becomes JSON true
- Python False becomes JSON false
- Python None becomes JSON null
This function is essential when you need to serialize Python data for storage or transmission in a JSON format, such as when working with APIs or storing configuration data.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Challenge
EasyCreate a function that takes a Python object as input and returns a formatted JSON string with specific indentation and separators. The function should:
- Use
json.dumps()to convert the input object to a JSON string. - Set the indentation to 4 spaces.
- Use a comma and a space (", ") as the item separator and a colon and a space (": ") as the key separator.
- Ensure that all keys in the resulting JSON string are sorted alphabetically.
The following input will be provided:
{"name": "Alice", "age": 30, "city": "New York", "hobbies": ["reading", "painting"], "is_student": false}
Print the resulting formatted JSON string.
Try it yourself
import json
# Read input
input_str = input()
input_obj = json.loads(input_str)
# TODO: Write your code here
# Create a function that formats the input_obj as a JSON string
# with the specified requirements
# Print the result
print(result)