Formatting JSON Output
Lesson 5 of 9 in Coddy's Python JSON course.
When working with JSON data, it's often useful to format the output for better readability. Python's json.dumps() function provides parameters to control the formatting of JSON output, making it more human-readable. This process is often called "pretty-printing".
The indent Parameter
The indent parameter in json.dumps() allows you to specify the number of spaces for indentation. This creates a more readable, hierarchical structure:
import json
data = {"name": "John", "age": 30, "city": "New York"}
# Without indentation
print(json.dumps(data))
# With indentation
print(json.dumps(data, indent=2))
The output with indent=2 will be:
{
"name": "John",
"age": 30,
"city": "New York"
}
The separators Parameter
The separators parameter allows you to specify the separators for items and key-value pairs. It's a tuple of two strings: (item_separator, key_separator).
# Default separators
print(json.dumps(data, indent=2))
# Custom separators
print(json.dumps(data, indent=2, separators=(', ', ': ')))
The default separators are (', ', ': '). You can use this parameter to make the output more compact or to add extra spacing.
Combining Parameters
You can combine these parameters for fine-tuned control over the JSON output:
formatted_json = json.dumps(data, indent=4, separators=(', ', ': '))
print(formatted_json)
This combination provides a nicely formatted, easy-to-read JSON output, which is particularly useful when working with complex nested structures or when you need to present JSON data in a more human-readable format.
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 formats a nested JSON structure with custom indentation and separators. The function should:
- Accept three parameters: a Python dictionary or list, an indentation level, and a boolean flag for compact output.
- Use
json.dumps()to convert the input to a JSON string. - Set the indentation to the specified level if the compact flag is False, otherwise use no indentation.
- Use a comma followed by a space (", ") as the item separator and a colon followed by a space (": ") as the key separator when the compact flag is False. Use a comma (",") and a colon (":") without spaces when the compact flag is True.
- Return the formatted JSON string.
The following input will be provided:
{"menu": {"id": "file", "value": "File", "popup": {"menuitem": [{"value": "New", "onclick": "CreateNewDoc()"}, {"value": "Open", "onclick": "OpenDoc()"}, {"value": "Close", "onclick": "CloseDoc()"}]}}}
4
false
Print the resulting formatted JSON string.
Try it yourself
import json
# Read input
json_input = input()
indent_level = int(input())
compact = input().lower() == 'true'
# Parse the JSON input
data = json.loads(json_input)
def format_json(data, indent, compact):
# TODO: Write your code here
# Implement the custom JSON formatting function
pass
# Format the JSON and print the result
formatted_json = format_json(data, indent_level, compact)
print(formatted_json)