【问题标题】:Save data in JSON file将数据保存在 JSON 文件中
【发布时间】:2020-07-15 14:38:57
【问题描述】:

我在下面的代码中遗漏了一些东西,无法以正确的格式保存,请您指导我哪里出错了...

Python 代码

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

expiy.json 中的输出

"23JUL2020"

我想以以下格式存储它,而不是得到需要更正的内容..

{"expirydate": "23JUL2020"}

【问题讨论】:

    标签: python json


    【解决方案1】:
    str_next_thursday_expiry = "23JUL2020"
    with open("data/expiry.json", "w") as f:
        data = {"expirydate":str_next_thursday_expiry}
        json.dump(data, f)
    

    【讨论】:

      【解决方案2】:

      试试这个

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

      【讨论】:

      • 谢谢尝试了这个但仍然保存为“23JUL2020”而不是“expirydate”:“23JUL2020”
      猜你喜欢
      • 2022-01-16
      • 2019-02-13
      • 2019-09-28
      • 2021-05-05
      • 1970-01-01
      • 1970-01-01
      • 2020-12-28
      • 1970-01-01
      • 2020-12-17
      相关资源
      最近更新 更多