Home > Mobile >  How do I print a .json file in python
How do I print a .json file in python

Time:01-08

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)

CodePudding user response:

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)

CodePudding user response:

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

  •  Tags:  
  • Related