如何使用python在JSON格式的文件中编写响应?

问题描述 投票:0回答:2

我试图以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))

This code give the same result with unicode character no indent

       with open('17octenv71232111.json', 'w') as outfile:
           json.dump(data,outfile)
           outfile.close()

This code also same result with unicode char and no indent

任何人都可以帮助我是否有任何可以进行格式化工作的库或任何可以提供帮助的代码。

python json file-read
2个回答
2
投票

函数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


1
投票
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))
© www.soinside.com 2019 - 2024. All rights reserved.