Python 为什么会这样'/';在我的json中

Python 为什么会这样'/';在我的json中,python,Python,我有这个 import json header = """{"fields": [""" print(header) with open('fields.json', 'w') as outfile: json.dump(header, outfile) 返回打印时,一切正常: {"fields": [ 但是fields.json中是什么呢 "{\"fields\": [" 为什么以及如何解决它 谢谢这里没有问题。文件中的\用于转义“。若要查看此内容,请将json读回并打印出

我有这个

import json

header = """{"fields": ["""

print(header)

with open('fields.json', 'w') as outfile:
    json.dump(header, outfile)
返回打印时,一切正常:

{"fields": [
但是fields.json中是什么呢

"{\"fields\": ["
为什么以及如何解决它


谢谢

这里没有问题。文件中的
\
用于转义
。若要查看此内容,请将
json
读回并打印出来。因此,要添加到代码中

import json

header = """{"fields": ["""

print(header)

with open('C:\\Users\\tkaghdo\\Documents\\fields.json', 'w') as outfile:
    json.dump(header, outfile)

with open('C:\\Users\\tkaghdo\\Documents\\fields.json') as data_file:
    data = json.load(data_file)

print(data)

您将看到数据打印为
{“字段”:[

您尝试编写的JSON被视为字符串
所以
被转换为
\”
。为了避免在写入文件之前需要使用
json.loads()
对json进行解码
json应该是完整的,否则
json.loads()
将抛出错误

import json

header = """{"name":"sk"}"""
h = json.loads(header)
print(header)

with open('fields.json', 'w') as outfile:
    json.dump(h, outfile)

首先,它不是
/
,而是
\

其次,它不在JSON中,因为这里似乎没有JSON,只有一个字符串。而
JSON.dump()
将字符串转换为JSON格式的转义字符串,将所有
替换为
\”


顺便说一句,您不应该尝试自己将不完整的JSON编写为字符串,最好只是制作一个字典
{“fields”:[]}
,然后用您想要的所有值填充它,然后通过
JSON.dump()保存到文件中

引号图表的转义序列它们是转义字符,用于转义引号。您实际试图用标题存档什么?您的问题标题询问“/”,但您的数据显示“\”。您询问的是哪一个字符,因为这两个字符在某些上下文中具有非常不同的含义。