Python - Pretty Print JSON - GeeksforGeeks (2024)

JSONstands forJavaScriptObjectNotation. It is a format for structuring data. This format is used by different web applications to communicate with each other.In this article, we will learn about JSON pretty print

What is JSON?

JSON (JavaScript Object Notation) is a text-based data format that is interchangeable with many programming languages. It is commonly used for data transmission between client-server applications. Usually, minified versions of JSON text are transmitted to save bandwidth. However, for debugging and analysis, a beautified version or a pretty print JSON is required. Essentially, pretty print JSON means having proper indentation, white spaces, and separators.

Example:

Input:'[ {"studentid": 1, "name": "ABC", "subjects": ["Python", "Data Structures"]}]' Output:[ { "studentid": 1, "name": "ABC", "subjects": [ "Python", "Data Structures" ] }]

json.dumps() in Python

First, use json.loads() method to convert JSON String to Python object. To convert this object to a pretty print JSON string, the json.dumps() method is used. Below are examples and steps to better understand these cases.

Syntax: json.dumps(obj, indent,separator)

Parameter:

  • obj: Serialize obj as a JSON formatted stream
  • indent: If indent is a non-negative integer or string, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0, negative, or “” will only insert newlines.
  • separators : If specified, separators should be an (item_separator, key_separator) tuple.

Pretty Print JSON String

This method has the parameter indent to specify the number of spaces and a separator parameter to specify the separator between key and value. By default, the separator is a comma between key-value pairs and a colon between key and value. If the indent parameter of json.dumps() is negative, 0, or an empty string then there are no indentations and only newlines are inserted. By default, the indent is None and the data is represented in a single line.

The code takes a JSON string containing student records, parses it into a Python data structure, then pretty-prints the JSON data with proper indentation for improved readability.

Python3

import json

json_data = '[ {"studentid": 1, "name": "ABC", \

"subjects": ["Python", "Data Structures"]}, \

{"studentid": 2, "name": "PQR",\

"subjects": ["Java", "Operating System"]} ]'

obj = json.loads(json_data)

json_formatted_str = json.dumps(obj, indent=4)

print(json_formatted_str)

Output:

[ { "studentid": 1, "name": "ABC", "subjects": [ "Python", "Data Structures" ] }, { "studentid": 2, "name": "PQR", "subjects": [ "Java", "Operating System" ] }]

Pretty-Printed JSON data into a file with indent=0.

The code takes a JSON string containing student records, parses it into a Python data structure, and then pretty-prints the JSON data with zero indentation, making it compact and less readable.

Python3

import json

json_data = '[ {"studentid": 1, "name": "ABC", \

"subjects": ["Python", "Data Structures"]},\

{"studentid": 2, "name": "PQR", \

"subjects": ["Java", "Operating System"]} ]'

obj = json.loads(json_data)

json_formatted_str = json.dumps(obj, indent=0)

print(json_formatted_str)

Output:

[{"studentid": 1,"name": "ABC","subjects": ["Python","Data Structures"]},{"studentid": 2,"name": "PQR","subjects": ["Java","Operating System"]}]

Write Pretty Print JSON data to file

To write a Python object as JSON Pretty Print format data into a file, json.dump() method is used. Like json.dumps() method, it has the indents and separator parameters to write beautified JSON.

Python3

import json

data = [{"studentid": 1, "name": "ABC",

"subjects": ["Python", "Data Structures"]},

{"studentid": 2, "name": "PQR",

"subjects": ["Java", "Operating System"]}]

with open("filename.json", "w") as write_file:

json.dump(data, write_file, indent=4)

Output:

Python - Pretty Print JSON - GeeksforGeeks (1)

filename.json

Reading JSON data and pretty print it

To read JSON from a file or URL, use json.load(). Then use json.dumps() to convert the object (obtained from reading the file) into a pretty print JSON string.

Python3

import json

with open("filename.json", "r") as read_file:

obj = json.load(read_file)

pretty_json = json.dumps(obj, indent=4)

print(pretty_json)

Output:

[ { "studentid": 1, "name": "ABC", "subjects": [ "Python", "Data Structures" ] }, { "studentid": 2, "name": "PQR", "subjects": [ "Java", "Operating System" ] }]

Using pprint module to pretty-print JSON to print our JSON format

This code reads JSON data from a file called “test.json,” parses it into a Python data structure, and then prints it using both the built-in print function and the pprint module. The pprint module is used to pretty-print the JSON data with specific formatting options like an indentation of 2, a line width of 30 characters, and compact representation.

Python3

import json

import pprint

with open("test.json", "r") as json_data:

student = json.load(json_data)

print(student)

print("\n")

pp = pprint.PrettyPrinter(indent=2, width=30, compact=True)

print("Pretty Printing using pprint module")

pp.pprint(student)

Output:

{'Teacher_id': 1, 'name': 'Suraj', 'Salary': 50000, 'attendance': 80, 'Branch': ['English', 'Geometry', 'Physics', 'World History'], 'email': '[email protected]'}Pretty Printing using pprint module("{'Teacher_id': 1, 'name': " "'Suraj', 'Salary': 50000, " "'attendance': 80, " "'Branch': ['English', " "'Geometry', 'Physics', " "'World History'], 'email': " "'[email protected]'}")

Pretty-print JSON from the command line

In this example, we are trying to print data using the command line. To validate and pretty-print JSON objects from the command line, Python offers the json.tool package.

Python3

echo {"studentid": 1, "name": "ABC",

"subjects": ["Python", "Data Structures"]} | python -m json.tool

Output:

{ "studentid": 1, "name": "ABC", "subjects": [ "Python", "Data Structures" ]}


A

akshisaxena

Python - Pretty Print JSON - GeeksforGeeks (2)

Improve

Next Article

Pretty Print JSON in Python

Please Login to comment...

Python - Pretty Print JSON - GeeksforGeeks (2024)
Top Articles
How Long Do Hard Inquiries Stay on Your Credit Report? | Capital One
Scale-out vs. Scale-up: What’s the Difference?
Jail Inquiry | Polk County Sheriff's Office
Duralast Gold Cv Axle
Odawa Hypixel
Uti Hvacr
Chatiw.ib
Trabestis En Beaumont
Crossed Eyes (Strabismus): Symptoms, Causes, and Diagnosis
Aiken County government, school officials promote penny tax in North Augusta
Cvs Devoted Catalog
Over70Dating Login
Nestle Paystub
Zoebaby222
Ave Bradley, Global SVP of design and creative director at Kimpton Hotels & Restaurants | Hospitality Interiors
Whitley County Ky Mugshots Busted
Learn2Serve Tabc Answers
Available Training - Acadis® Portal
Mineral Wells Independent School District
Google Flights Missoula
Free Online Games on CrazyGames | Play Now!
How to Create Your Very Own Crossword Puzzle
Band Of Loyalty 5E
10 Fun Things to Do in Elk Grove, CA | Explore Elk Grove
Nevermore: What Doesn't Kill
Loft Stores Near Me
Blue Rain Lubbock
Toyota Camry Hybrid Long Term Review: A Big Luxury Sedan With Hatchback Efficiency
Shiftselect Carolinas
Tu Pulga Online Utah
A Cup of Cozy – Podcast
Southwest Flight 238
§ 855 BGB - Besitzdiener - Gesetze
UPC Code Lookup: Free UPC Code Lookup With Major Retailers
Ducky Mcshweeney's Reviews
Senior Houses For Sale Near Me
Royals op zondag - "Een advertentie voor Center Parcs" of wat moeten we denken van de laatste video van prinses Kate?
Wsbtv Fish And Game Report
Dying Light Nexus
Devotion Showtimes Near The Grand 16 - Pier Park
Empires And Puzzles Dark Chest
SF bay area cars & trucks "chevrolet 50" - craigslist
Updates on removal of DePaul encampment | Press Releases | News | Newsroom
If You're Getting Your Nails Done, You Absolutely Need to Tip—Here's How Much
At Home Hourly Pay
DL381 Delta Air Lines Estado de vuelo Hoy y Historial 2024 | Trip.com
Marcel Boom X
Stephen Dilbeck, The First Hicks Baby: 5 Fast Facts You Need to Know
Ihop Deliver
Craigslist Anc Ak
Latest Posts
Article information

Author: Amb. Frankie Simonis

Last Updated:

Views: 6020

Rating: 4.6 / 5 (76 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Amb. Frankie Simonis

Birthday: 1998-02-19

Address: 64841 Delmar Isle, North Wiley, OR 74073

Phone: +17844167847676

Job: Forward IT Agent

Hobby: LARPing, Kitesurfing, Sewing, Digital arts, Sand art, Gardening, Dance

Introduction: My name is Amb. Frankie Simonis, I am a hilarious, enchanting, energetic, cooperative, innocent, cute, joyous person who loves writing and wants to share my knowledge and understanding with you.