在 Python 中更新 JSON 文件

luc*_*llo 2 python json

我要更新的 .json 文件具有以下结构:

{
  "username": "abc",
  "statistics": [
    {
      "followers": 1234,
      "date": "2018-02-06 02:00:00",
      "num_of_posts": 123,
      "following": 123
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

我希望它像这样插入一个新的统计数据

{
  "username": "abc",
  "statistics": [
    {
      "followers": 1234,
      "date": "2018-02-06 02:00:00",
      "num_of_posts": 123,
      "following": 123
    },
    {
      "followers": 2345,
      "date": "2018-02-06 02:10:00",
      "num_of_posts": 234,
      "following": 234
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

当与

with open(filepath, 'w') as fp:
    json.dump(information, fp, indent=2)
Run Code Online (Sandbox Code Playgroud)

该文件将始终被覆盖。但我希望添加统计中的项目。我尝试以多种可能的方式读取文件并在之后附加它,但它从未奏效。

数据即将写入信息变量中,就像

information = {
  "username": username,
  "statistics": [
      {
          "date": datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
          "num_of_posts": num_of_posts,
          "followers": followers,
          "following": following
      }
  ]
}
Run Code Online (Sandbox Code Playgroud)

那么如何更新我的信息添加正确的 .json 文件呢?

Jes*_*per 5

你会想要做一些事情:

def append_statistics(filepath, num_of_posts, followers, following):

    with open(filepath, 'r') as fp:
        information = json.load(fp)

    information["statistics"].append({
        "date": datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
        "num_of_posts": num_of_posts,
        "followers": followers,
        "following": following
    })

    with open(filepath, 'w') as fp:
        json.dump(information, fp, indent=2)
Run Code Online (Sandbox Code Playgroud)