“JSON is a popular data-interchange format that has been widely adopted across the development community. However, JSON has strict schema and formatting tools.
JSON does not natively support multi-line strings. This can be quiebro frustrating when looking for flexibility and storing large texts.
Let us discuss a simple workaround and how we can use multiline strings.”
Using a JSON Array
A creative way of inserting a multi-line string in JSON is to use an array. We can separate each line as an individual element of the array.
For example, let us say we have a sample text as shown:
Lorem ipsum dolor sit amet. Aut eveniet sequi sit sequi dicta vel impedit architecto 33 voluptas tempore et optio libero qui molestiae possimus. Aut cupiditate animi ut commodi natus ut nesciunt mollitia ea ipsam iusto a ipsa odit a laboriosam neque et vero totam.
If we want to convert the above block of text into JSON, we can convert each line into an array element.
For example:
[ «Lorem ipsum dolor sit amet.», «Aut eveniet sequi sit sequi dicta vel impedit architecto,», «33 voluptas tempore et optio libero qui molestiae possimus.», «Aut cupiditate animi ut commodi natus ut nesciunt mollitia ea,», «ipsam iusto a ipsa odit a laboriosam neque et vero totam.» ]
Note how each line of the above string is converted into an array element separated by a comma.
You can then use a method in your preferred programming language to construct the string back to its individual block.
Conclusion
This tutorial provides a simple but creative way of creating a multi-line string in JSON.
“JSON or JavaScript Object Notation is a lightweight data exchange format that is widely adopted by modern applications. Whether you are working in NoSQL databases or fetching API data, you will encounter JSON.
It is a heavily adopted language due to its simplicity but strict schema. This helps to reduce errors while still retaining human readability.
Luckily, Python has a built-in package called json that allows us to interact and process JSON data.
For this tutorial, we will cover how you can pretty-print JSON data using Python’s json module.”
Let’s get started.
Python json.dumps() Function
To pretty print JSON data in Python, we use the dumps method from the json module. The function syntax is as shown:
obj – refers to the JSON object you wish to print.
skipkeys – if set to true, the function will skip keys that are not of str, int, float, bool, or None type. This value is set to false by default.
ensure_ascii – if set to true, the function will return an output with non-ascii characters escaped. This value is true by default.
check_circular – skips the circular reference check for container types if true. Otherwise, return OverFlowError.
allow_nan – out of range floats are substituted for NaN, Infinity, or -Inifinity if set to true.
indent – specifies the indent level for the pretty-print format. If the indent level is 0 or negative, the function will only print new lines. For a more compact representation of the data, ensure to specify a positive integer of above 1.
separators – specify the item and key separate characters.
sort_keys – if true, the function sorts the output dictionary by its keys.
Let us explore how we can use this function to pretty-print JSON data.
Example 1
The example below shows how to use the json.dumps() function to pretty-print a JSON object.
1 2 3 4 5 6 7 8 9 10 11
from json import dumps, loads
data =‘{«id»:1,»first_name»:»Jada»,»last_name»:»Deport»,»email»:»[email protected]«,»gender»:»Female»,»ip_address»:»68.40.159.153″}’
json_object = loads(data)
print(dumps(json_object, indent=3))
We start by importing the required functions. In our case, we need the dumps() function to pretty-print the json object and the loads to deserialize the json into a Python object.
Next, we create a variable holding the raw JSON data. We convert it into a Python object using the loads’ function and finally, pretty print it with the dumps() function.
The code should sort the keys of the output dictionary in ascending order as shown:
Note how each key in the resulting dictionary is sorted in alphabetical order.
Example 3 – Pretty Print JSON From File
Using Python’s open function, we can load data from a JSON file and pretty print it. Suppose we have a JSON file as shown:
We can load the file and use the json.dumps() method as shown in the example code below:
1 2 3 4 5 6 7
from json import dumps, load
withopen(‘net_info.json’,‘r’)as f:
json_data = load(f)
print(dumps(json_data, indent=1))
In the example above, we use the load function to load the JSON data from the file into a JSON object.
We then use the dumps function to pretty print with an indent level of 1. The resulting output is as shown:
The output gives us a well-formatted list of Python dictionaries representing the JSON data.
Conclusion
In this tutorial, we learned how to use the JSON dumps function to pretty-print JSON data in Python. We also learned how to sort JSON data by its keys using the sort_keys parameter.