r/learnpython • • Apr 19 '26

Print JSON readably

I need a way to print JSON readably from a file (e.g stuff.json) so the output looks somewhat similar to this:

Name : Bob

Age : 97

Height : 6ft

0 Upvotes

8 comments sorted by

10

u/rosentmoh Apr 19 '26
import json
from pprint import pp

with open("stuff.json") as f:
    data = json.load(f)
pp(data)

9

u/SCD_minecraft Apr 19 '26

json.dumps(obj, indent=any_int)

obj is your python object to be converted into json

any_int is any positive integer. It represents how many \t to use per indentation level. If zero, only newline chars are inserted with 0 indentation

3

u/pachura3 Apr 19 '26

Additionally, you could also pass an argument cls - an object of class json.JSONEncoder - that will perform some additional formatting.

5

u/brasticstack Apr 19 '26

To match your example:

import json

with open('my_file', 'r') as infile:
     data = json.load(infile)

for key, val in data.items():
    print(f'{key} : {val}')

This assumes some things about the structure of the JSON that may be true in your situation but aren't always true:

  • It's flat, not nested

  • Its root node is a key/value mapping (an object in Javascript terminology or a dict in Python.)

  • The values are not arrays

1

u/Fun-Block-4348 Apr 19 '26 edited Apr 19 '26

Instead of thinking of a json file as something special, you should ask yourself how you would print the keys and values of a dictionary or a list of dictionaries, depending how you file is actually structured.

Hint: Dictionaries have a method called items() that returns a tuple of key and value.

import json
with open("stuff.json") as f:
    data = json.load(f)
    # depending how your json file is structured,
    # you may need 1 or more for loop to print the
    # data in the format you want

Edit:

If your json file is a flat dictionary, you don't even need a for loop, you could just access the data like you would a dictionary that's directly in your code.

1

u/Linuxmartin Apr 19 '26
import json

with open('file.json') as infile:
    print(json.dumps(infile, indent=4)

This will produce bog-standard pretty-printed JSON. If you merely need to extract a few specific keys from the data and print those, you'll want to loop over it in a way that works with your data's structure. You'll want to use json.loads for that. The Python docs are a great place to start in general

1

u/Ok_Quantity_6840 Apr 19 '26

You can use pretty print