【问题标题】:Json keeping added keys together without creating new dictsJson 将添加的键放在一起而不创建新的字典
【发布时间】:2018-08-29 05:25:23
【问题描述】:

我正在尝试弄清楚如何将添加在一起的键保存在一起。我编写了这个小脚本,每次运行时都会添加键和值,但它会不断添加字典。

import json
import datetime

key = str(datetime.datetime.now())
insert = 'Test'
logged = {key : insert}

data = json.load(open('StartLog.json', 'r'))
with open('StartLog.json', 'w') as f:
    data['Logs'].append(logged)
    json.dump(data, f, indent=2)

当前的输出是:

{
  "Logs": [
    {
      "2018-08-28 22:07:12.540188": "Test"
    },
    {
      "2018-08-28 22:07:20.134817": "Test"
    }
  ]
}

我希望输出是:

{
  "Logs": [
    {
      "2018-08-28 22:07:12.540188": "Test",
      "2018-08-28 22:07:20.134817": "Test"
    }
  ]
}

【问题讨论】:

    标签: python json python-3.x


    【解决方案1】:

    data 中的Logs 更改为字典并使用每个条目更新字典:

    import json
    import datetime
    
    key = str(datetime.datetime.now())
    insert = 'Test'
    logged = {key : insert}
    
    data = json.load(open('StartLog.json', 'r'))
    with open('StartLog.json', 'w') as f:
        data['Logs'].update(logged)
        json.dump(data, f, indent=2)
    

    所以StartLog.json 的开头应该是:

    {
      "Logs": {
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-05-06
      • 1970-01-01
      • 1970-01-01
      • 2021-03-14
      • 1970-01-01
      • 2015-05-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-15
      相关资源
      最近更新 更多