提问者:小点点

使用Python在JSON文件中保存数据


我在下面的代码中丢失了一些东西,不能以正确的格式保存,你能指导我在哪里走错了吗。。。

Python代码

str_next_thursday_expiry=23jul2020

f=open(“data/expire.json”,“r”)

打开(“data/expire.json”,“w”)为f:json.dump(SR_NEXT_TURSDAY_EXPIRY,f)

expiy.json中的输出

“23jul2020”

我想存储在下面的格式,没有得到什么需要更正。。

{“expirydate”:“23jul2020”}

事先非常感谢。。。

问好,RJ


共2个答案

匿名用户

str_next_thursday_expiry = "23JUL2020"
with open("data/expiry.json", "w") as f:
    data = {"expirydate":str_next_thursday_expiry}
    json.dump(data, f)

匿名用户

试试这个

content = {"expirydate": "23JUL2020"}
with open("data/expiry.json", "w") as f:
    json.dump(str_next_thursday_expiry, f)