Q:

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. 
Example: I would like to add player_two, player_three through python.
{
  "players": {
    "player_one": {
      "name": "Bob",
      "age": "0",
      "email": "bob@example.com"
    }
  }
}

How can I achieve doing this through python?
What I've tried: 
with open("/var/www/html/api/toons/details.json", 'w') as outfile:
                json.dump(avatarDetails, outfile)

A:

Here is a simple example, read the file as a dict, update the dict, then use json.dumps() to get the json data:
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"
        }
    }
}

