Python Pretty Print JSON
When we convert a string to JSON the data is in a less readable format. To make it more readable we can use pretty printing by passing additional arguments in json.dumps() function such as indent and sort_keys as used in the below code.
Python3
# Python program to convert JSON to Python import json # JSON string employee = '{"id":"09", "name": "Nitin", "department":"Finance"}' # Convert string to Python dict employee_dict = json.loads(employee) # Pretty Printing JSON string back print (json.dumps(employee_dict, indent = 4 , sort_keys = True )) |
{ "department": "Finance", "id": "09", "name": "Nitin" }
Read, Write and Parse JSON using Python
JSON is a lightweight data format for data interchange that can be easily read and written by humans, and easily parsed and generated by machines. It is a complete language-independent text format. To work with JSON data, Python has a built-in package called JSON.
Example of JSON String
s = '{"id":01, "name": "Emily", "language": ["C++", "Python"]}'
The syntax of JSON is considered a subset of the syntax of JavaScript including the following:
- Name/Value pairs: Represents Data, the name is followed by a colon(:), and the Name/Value pairs are separated by a comma(,).
- Curly braces: Holds objects.
- Square brackets: Hold arrays with values separated by a comma (,).
Keys/Name must be strings with double quotes and values must be data types amongst the following:
- String
- Number
- Object (JSON object)
- array
- Boolean
- Null
Example of JSON file:
{
"employee": [
{
"id": "01",
"name": "Amit",
"department": "Sales"
},
{
"id": "04",
"name": "sunil",
"department": "HR"
}
]
}