我试图以JSON格式存储来自API的响应。我以字符串格式获得JSON响应并存储在文件中。我们如何在onlineJSONViewer应用程序中看到它或使用缩进转换?或以JSON格式。
代码我曾经存储在一个文件中。
def test_url(self):
resp =requests.get(www.myurl.com)
data = resp.text
f = open("19octfile.json", "w")
f.write(data)
f.close()
此代码以下面的格式将响应存储在19octfile.json中:
{"data": [{"id":"myname","id":"123","name":"myname","user":"m3","provider":"user","region":"india"}]}
现在,我如何以缩进格式存储响应,即JSON格式,以便用户在读取时可以轻松理解。
我不同的尝试但是徒劳:
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()
任何人都可以帮助我是否有任何可以进行格式化工作的库或任何可以提供帮助的代码。
函数json.dumps接受命名参数indent
。从文档:
如果indent是一个非负整数,那么JSON数组元素和对象成员将使用该缩进级别进行漂亮打印。缩进级别为0或负数只会插入换行符。无(默认值)选择最紧凑的表示。
首先,您需要将json文件内容加载到python对象中。您当前的代码将json字符串传递给json.dumps。使用以下内容:
j = json.loads(data)
f.write(json.dumps(j, sort_keys=True, indent=4))
这里json.loads函数将json字符串转换为python对象,可以传递给json.dumps
。
import json
d={"data": [{"id":"myname","id":"123","name":"myname","user":"m3","provider":"user","region":"india"}]}
print(json.dumps(d,indent=2))
写入文件
with open('17octenv71232111.json', 'w') as outfile:
outfile.write(json.dumps(d,indent=2))