1

I am trying to add something to a .json file.

This is what saves

        "106569102398611456" : {
        "currentlocation" : "Pallet Town",
        "name" : "Anthony",
        "party" : [
            {
                "hp" : "5",
                "level" : "1",
                "pokemonname" : "bulbasaur"
            }
        ],
        "pokedollars" : 0
    }
}

What I'm trying to do is make a command to add something else to the "party". Here is an example of what I want.

    "106569102398611456" : {
        "currentlocation" : "Pallet Town",
        "name" : "Anthony",
        "party" : [
            {
                "hp" : "5",
                "level" : "1",
                "pokemonname" : "bulbasaur"
            },
            {
                "hp" : "3",
                "level" : "1",
                "pokemonname" : "squirtle"
            }

        ],
        "pokedollars" : 0
    }
}

edit:

This is what I've attempted but I have no idea

def addPokemon(pokemon):
    pokemonName = convert(pokemon)
    for pokemon in players['party']:
        pokemon.append(pokemonName)

convert(pokemon) basically grabs the pokemon i type in and change gives it a level and health to be added to the .json file

3
  • What's wrong with using the append() method? Commented May 24, 2016 at 1:37
  • and what have you tried? can you show us some code? any error message(s)? Commented May 24, 2016 at 1:37
  • I'm not too sure where to start adding extra stuff into the file Commented May 24, 2016 at 1:38

1 Answer 1

1

To update a JSON file, write out the object to a temporary file and then replace the target file with the temporary file. Example:

import json
import os
import shutil
import tempfile

def rewriteJsonFile(sourceObj, targetFilePath, **kwargs):
  temp = tempfile.mkstemp()
  tempHandle = os.fdopen(temp[0], 'w')
  tempFilePath = temp[1]
  json.dump(sourceObj, tempHandle, **kwargs)
  tempHandle.close()
  shutil.move(tempFilePath, targetFilePath)

This assumes that updates are happening serially. If updates are potentially happening in parallel, you'd need some kind of locking to ensure only one update is happening at a time. Although at that point, you're better off using a database like sqlite and returning queries in JSON format.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.