0

I was wondering if anyone knows how to print a .json file in python using the same formatting as if I was running it from JavaScript. I’m using it for api usage and the output is .json but when I print it I get this: link to image

However the api documentation has this: another image

(The images show different sections of it)

  • I think this is a formatting question. Take a look at [How to prettyprint a json file](https://stackoverflow.com/questions/12943819/how-to-prettyprint-a-json-file?rq=1). – MYousefi Jan 08 '22 at 05:50
  • 1
    Does this answer your question? [How to prettyprint a JSON file?](https://stackoverflow.com/questions/12943819/how-to-prettyprint-a-json-file) – MYousefi Jan 08 '22 at 05:52
  • [Please do not upload images of code/errors when asking a question.](//meta.stackoverflow.com/q/285551) This also applies to textual output from programs. Instead, copy and paste the data, formatted as code. If there's too much to show reasonably in this way, use a smaller input for the program. – Karl Knechtel Jan 08 '22 at 06:22

2 Answers2

2

I guess you mean how to print a json formatted, if so, you could do

import json
with open('yourfile.json', 'r') as handle:
    parsed = json.load(handle)
print(json.dumps(parsed, indent=4, sort_keys=True))

If you want to do it like Javascript there's a way

var str = JSON.stringify(YourJsonObject, null, 4);

Or another way

import json 
     
# Opening JSON file 
f = open('yourjsonfile.json',) 
     
# returns JSON object as  
# a dictionary 
data = json.load(f) 
     
print(json.dumps(data, indent = 4)
     
# Closing file 
f.close() 

Also

import json

print json.dumps(jsonstring, indent=4)
Skizo-ozᴉʞS ツ
  • 19,464
  • 18
  • 81
  • 148
2

This should do the trick:

import json
print(json.dumps(my_input, sort_keys=True, indent=4))

See https://docs.python.org/3/library/json.html

ljdyer
  • 1,946
  • 1
  • 3
  • 11