我想将字符串保存到json文件中,但是当我这样做时,它将用\"
并将其写在开头和结尾。
import json
name_c = ['Don', 'Perez']
my_details = "data = {" + "\"name\": " + name_c[0] + ", \"lastname\": " + name_c[1] + "}"
print(my_details)
with open('personal.json', 'w') as outfile:
json.dump(my_details, outfile)
我想要json文件中的这种文本:
data = {"name": Don, "lastname": Perez}
我在json文件中得到了这种文本
"data = {\"name\": Don, \"lastname\": Perez}"
答案 0 :(得分:2)
它是添加引号,因为您要转储字符串。无论该字符串表示什么,都可以完成此操作。如果要它转储对象,则必须给它一个要转储的对象。
答案 1 :(得分:1)
为什么不在文件中写字符串?
name_c = ['Don', 'Perez']
with open("out.txt", "w+") as f:
f.write("data = {{\"name\": {}, \"lastname\": {}}}".format(*name_c))
如果您想使用json,则可以这样:
name_c = ['Don', 'Perez']
with open("out.txt", "w+") as f:
f.write("data = ")
json.dump({"name": name_c[0], "lastname": name_c[1]}, f)
或者这个:
name_c = ['Don', 'Perez']
with open("out.txt", "w+") as f:
f.write("data = " + json.dumps({"name": name_c[0], "lastname": name_c[1]}))