简体   繁体   English

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

[英]Store new JSON data to existing file in python

I've been looking around the web and I cannot find a way on adding new JSON data to array. 我一直在网上浏览,找不到在数组中添加新JSON数据的方法。

Example: I would like to add player_two, player_three through python. 示例:我想通过python添加player_two,player_three。

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

How can I achieve doing this through python? 如何通过python实现此目的?

What I've tried: 我尝试过的

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

Here is a simple example, read the file as a dict, update the dict, then use json.dumps() to get the json data: 这是一个简单的示例,将文件作为字典读取,更新字典,然后使用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)

Now the file looks like: 现在文件看起来像:

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

Assuming that your file contains this JSON: 假设您的文件包含此JSON:

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

You can parse the data into a Python dictionary using json.load() : 您可以使用json.load()将数据解析为Python字典:

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

Add your new players: 添加您的新玩家:

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')

Then save it back to a file: 然后将其保存回文件:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM