Python JSON Serialization: From Objects to Strings
JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write and easy for machines to parse and generate. In Python, you often need to convert Python objects into JSON strings for tasks like sending data over a network, storing it in a file, or communicating with web APIs. This challenge will test your understanding of Python's json module for serializing various Python data structures into JSON.
Problem Description
Your task is to implement a function that takes a Python object (which can be a dictionary, list, string, number, boolean, or None) and serializes it into a JSON formatted string. You should leverage Python's built-in json module for this purpose.
Key Requirements:
- The function should accept a single argument: the Python object to be serialized.
- The function should return a JSON formatted string representing the input object.
- The output JSON string should be "pretty-printed," meaning it should have indentation for readability.
- Handle common Python data types correctly.
Expected Behavior:
The function should produce a valid JSON string that accurately represents the structure and values of the input Python object. The output should be indented with 4 spaces.
Edge Cases to Consider:
- What happens with
None? - How are numbers (integers and floats) handled?
- How are booleans handled?
- What about nested data structures (dictionaries within lists, lists within dictionaries)?
Examples
Example 1:
Input: {"name": "Alice", "age": 30, "isStudent": False, "courses": ["Math", "Science"]}
Output:
{
"name": "Alice",
"age": 30,
"isStudent": false,
"courses": [
"Math",
"Science"
]
}
Explanation: A dictionary with various data types is serialized into a pretty-printed JSON string. Python's `False` is correctly mapped to JSON's `false`.
Example 2:
Input: [1, 2, 3, None, {"key": "value"}]
Output:
[
1,
2,
3,
null,
{
"key": "value"
}
]
Explanation: A list containing numbers, None, and a nested dictionary is serialized. Python's `None` is mapped to JSON's `null`.
Example 3:
Input: 42.75
Output:
42.75
Explanation: A simple floating-point number is serialized directly.
Constraints
- The input object will be a standard Python data structure that is directly serializable by the
jsonmodule (i.e., no custom objects that require special handling likedatetimeorDecimalwithout further configuration). - The function must use Python's built-in
jsonmodule. - The output JSON string must be indented with exactly 4 spaces.
Notes
- The
jsonmodule in Python is your primary tool. Specifically, look for a function that converts a Python object to a JSON string. - Pay close attention to the arguments available in the
jsonmodule's serialization function to achieve "pretty-printing." - Consider how Python's native types map to JSON's standard types. For instance, Python's
Nonecorresponds to JSON'snull, and Python'sTrue/Falsecorrespond to JSON'strue/false.