import json
header = """{"fields": ["""
print(header)
with open('fields.json', 'w') as outfile:
json.dump(header, outfile)
和打印的回归它的确定:
{"fields": [
,但什么是在fields.json它
"{\"fields\": ["
为什么以及如何解决?
谢谢
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)
你将看到数据打印为{"fields": [
你试图写的JSON是带来视为字符串
所以"
转化为\"
。避免我们需要写入文件
JSON的应该是完整的之前使用json.loads()
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()
保存到文件中。
转义字符的转义序列 –
它们是转义字符,它们在那里以避免引号 – CoryKramer
实际上您试图使用标题存档? –