To pretty print JSON in Python, we can use the built-in json
module’s dumps
function, which stands for “dump string.”
This function takes a Python object (such as a dictionary or list) and converts it to a JSON string.
Here’s an example of using loads
and dumps
to pretty print a JSON string:
import json
json_str = '{"name":"John Smith","age":30,"isEmployed":true,"skills":["Python","JavaScript"]}'
json_obj = json.loads(data)
formatted_str = json.dumps(data, indent=2)
print(formatted_str)
Code language: Python (python)
The output of this code would be:
{
"name": "John Smith",
"age": 30,
"isEmployed": true,
"skills": [
"Python",
"JavaScript"
]
}
Code language: JSON / JSON with Comments (json)
As you can see, the JSON output is now much easier to read due to the added indentation. The indent
parameter specifies the number of spaces to use for indentation. You can adjust this value to increase or decrease the level of indentation.
If you have already have an object instead, such as a dictionary or list, you can skip the json.loads
step:
import json
data = {"name":"John Smith","age":30,"isEmployed":true,"skills":["Python","JavaScript"]}
json_data = json.dumps(data, indent=2)
print(json_data)
Code language: Python (python)
The output will be identical to the example above.
Customizing JSON Output with the sort_keys
Parameter
The dumps
function also has a sort_keys
parameter that can be used to sort the keys in a JSON object. By default, the keys are not sorted, but you can set sort_keys=True
to sort the keys alphabetically.
Here’s an example of using the sort_keys
parameter:
import json
data = {"name":"John Smith","age":30,"isEmployed":true,"skills":["Python","JavaScript"]}
formatted_str = json.dumps(data, indent=2, sort_keys=True)
print(formatted_str)
Code language: Python (python)
The output of this code would be:
{
"age": 30,
"isEmployed": true,
"name": "John Smith",
"skills": [
"Python",
"JavaScript"
]
}
Code language: JSON / JSON with Comments (json)
JSON.dumps Syntax and Arguments
The json.dumps()
function is used to convert a Python object (such as a dictionary or list) into a JSON string. Here is the basic syntax for json.dumps()
:
json.dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)
Code language: Python (python)
Here is a breakdown of the arguments that json.dumps()
can take:
obj
: The Python object to be serialized.skipkeys
: If set toTrue
,json.dumps()
will skip keys that are not of a basic data type (such as strings or numbers). If set toFalse
, an error will be raised for these types of keys.ensure_ascii
: If set toTrue
, all non-ASCII characters will be escaped in the JSON output. If set toFalse
, non-ASCII characters will be output as-is.check_circular
: If set toTrue
,json.dumps()
will check for circular references in the object being serialized and raise an error if any are found. If set toFalse
, circular references will not be checked.allow_nan
: If set toTrue
,NaN
,Infinity
, and-Infinity
values will be serialized as the corresponding JSON values. If set toFalse
, an error will be raised for these values.cls
: A custom JSONEncoder class to use for serialization.indent
: The number of spaces to use for indentation when pretty printing the JSON output. If set toNone
, the JSON output will not be indented.separators
: A tuple of strings to use as separators between keys and values, and between elements in an array.default
: A function that takes an object and returns a serializable version of it.sort_keys
: If set toTrue
, the keys in the JSON object will be sorted alphabetically. If set toFalse
, the keys will be output in the order they appear in the object.
By using these arguments, you can customize the behavior of json.dumps()
to suit your needs. For example, you can use the indent
argument to pretty print the JSON output, or the sort_keys
argument to alphabetize the keys in the JSON object.
Conclusion
In this article, we explored how to use Python’s json
module to pretty print JSON output. We looked at how to use the dumps
function’s indent
and sort_keys
parameters to customize the output.
With these tools, you should be able to easily format JSON output in a way that is easy to read and understand.
Leave a Reply