为什么json.dump会在vscode中产生行尾?

2024-10-03 00:22:29 发布

您现在位置:Python中文网/ 问答频道 /正文

with open('weather.json', 'w') as json_file:
            json.dump(response.text, json_file, separators=(", ", ": "), sort_keys=True, ensure_ascii=True)

weather.json = "{\"meta\":{\"exec_time\":0.021,\"generated\":\"2020-07-04 19:07:54\"},\"data\":[{\"id\":\"KHBI0\",\"name\":{\"en\":\"Asheboro \\/ Cedar Grove\"},\"active\":true,\"distance\":8.4}]}"

我用ValueError尝试了pd.read_json:未正确调用数据帧构造函数

也试着换了

data = weather.json
data.replace('\\', '')

和检索字符串,但vscode仍然不能识别为json文件,并且不能很好地打印

ouput: {"meta":{"exec_time":0.021,"generated":"2020-07-04 19:07:54"},"data":[{"id":"KHBI0","name":{"en":"Asheboro / Cedar Grove"},"active":true,"distance":8.4}]}

Tags: nameidjsontruedatatimemetagenerated
1条回答
网友
1楼 · 发布于 2024-10-03 00:22:29

json.dump(response.text)。。。你为什么要序列化文本

您已将表示JSON的字符串序列化为JSON字符串。所以它将被反序列化为字符串

考虑:

>>> import json
>>> data = '{"foo":42}'
>>> type(data)
<class 'str'>
>>> data["foo"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: string indices must be integers
>>> serialized = json.dumps(data)
>>> print(serialized)
"{\"foo\":42}"

因此,当您反序列化它时:

>>> deserialized = json.loads(serialized)
>>> deserialized
'{"foo":42}'
>>> type(deserialized)
<class 'str'>

你几乎肯定只想:

with open('weather.json', 'w') as f:
    f.write(response.text)

注意,所有这些都与VS代码无关

相关问题 更多 >