Reputation: 169
I am trying to store the response from API in JSON format. I got the JSON response in a string format and stored in a file. How do I make it or convert with indent as we see in the onlineJSONViewer application? or in JSON format.
Code I used to store in a file.
def test_url(self):
resp =requests.get(www.myurl.com)
data = resp.text
f = open("19octfile.json", "w")
f.write(data)
f.close()
This Code stores the response in 19octfile.json in below format:
{"data": [{"id":"myname","id":"123","name":"myname","user":"m3","provider":"user","region":"india"}]}
Now, How can I store the response with indent i.e in JSON format so that user can understand easily when reads.
My different TRY but in vain:
with codecs.open('data.json', 'w', 'utf8') as f:
f.write(json.dumps(data, sort_keys=True, ensure_ascii=False))
with open('17octenv71232111.json', 'w') as outfile:
json.dump(data,outfile)
outfile.close()
Can any one help me is there any library that can do the format work or any code to help.
Upvotes: 3
Views: 8234
Reputation: 8273
import json
d={"data": [{"id":"myname","id":"123","name":"myname","user":"m3","provider":"user","region":"india"}]}
print(json.dumps(d,indent=2))
To write to file
with open('17octenv71232111.json', 'w') as outfile:
outfile.write(json.dumps(d,indent=2))
Upvotes: 2
Reputation: 10074
The function json.dumps accepts a named parameter indent
. From the documentation:
If indent is a non-negative integer, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0, or negative, will only insert newlines. None (the default) selects the most compact representation.
First you need to load the json file contents into a python object. Your current code is passing the json string to json.dumps. Use the following:
j = json.loads(data)
f.write(json.dumps(j, sort_keys=True, indent=4))
Here the json.loads function turns the json string into a python object which can be passed to json.dumps
.
Upvotes: 5