将新的JSON数据存储在python中的现有文件中

时间:2015-11-08 04:36:31

标签: python json

我一直在寻找网络,我找不到将新的JSON数据添加到数组的方法。

示例:我想通过python添加player_two,player_three。

{
  "players": {
    "player_one": {
      "name": "Bob",
      "age": "0",
      "email": "bob@example.com"
    }
  }
}

我如何通过python实现这一目标?

我尝试过的事情:

with open("/var/www/html/api/toons/details.json", 'w') as outfile:
                json.dump(avatarDetails, outfile)

2 个答案:

答案 0 :(得分:2)

这是一个简单的例子,将文件作为dict读取,更新dict,然后使用json.dumps()获取json数据:

import json

# open your jsonfile in read mode
with open('jsonfile') as f:
    # read the data as a dict use json.load()
    jsondata = json.load(f)

# add a new item into the dict
jsondata['players']['player_two'] = {'email': 'kevin@example.com', 'name': 'Kevin', 'age': '0'}

# open that file in write mode
with open('jsonfile', 'w') as f:
    # write the data into that file
    json.dump(jsondata, f, indent=4, sort_keys=True)

现在文件看起来像:

{
    "players": {
        "player_one": {
            "age": "0",
            "email": "bob@example.com",
            "name": "Bob"
        },
        "player_two": {
            "age": "0",
            "email": "kevin@example.com",
            "name": "Kevin"
        }
    }
}

答案 1 :(得分:1)

假设您的文件包含此JSON:

{
  "players": {
    "player_one": {
      "name": "Bob",
      "age": "0",
      "email": "bob@example.com"
    }
  }
}

您可以使用json.load()将数据解析为Python字典:

with open('/var/www/html/api/toons/details.json') as f:
    data = json.load(f)

添加新玩家:

data['players']['player_two'] = dict(name='Bobbie', age=100, email='b@blah.com')
data['players']['player_three'] = dict(name='Robert', age=22, email='robert@blah.com')

然后将其保存回文件:

with open('/var/www/html/api/toons/details.json', 'w') as f:
    json.dump(data, f)