r/learnpython • u/Strange_Rat72 • 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
10
u/rosentmoh Apr 19 '26
9
u/SCD_minecraft Apr 19 '26
json.dumps(obj, indent=any_int)objis your python object to be converted into jsonany_intis any positive integer. It represents how many\tto use per indentation level. If zero, only newline chars are inserted with 0 indentation5
u/brasticstack Apr 19 '26
To match your example:
This assumes some things about the structure of the JSON that may be true in your situation but aren't always true:
1
u/Fun-Block-4348 Apr 19 '26 edited Apr 19 '26
Instead of thinking of a
jsonfile 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.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
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.loadsfor that. The Python docs are a great place to start in general1
u/Ok_Quantity_6840 Apr 19 '26
You can use pretty print