Search code examples
pythonregexjsonupdating

Is there an easy way to edit a json file with python


There are some similar questions to this lying around but I couldn't find anything that does what I'm looking for.

The code I'm using is as follows (python 2.75): (EDIT, updated to include suggestions for clarity:

def write_json(entry):
  current_players = []
  with open("Dota2data.txt","r+") as outfile:
     data = json.load(outfile)
     for member in entry.players:
        current_players.append(member['account_id'])
     data["matches"].append({"match":entry.match_id, "winner":entry.radiant_win, "players":current_players})
     json.dump(data, outfile)
     outfile.close()
  pass

I'm basically trying to add a new match instance within the 'matches' key each time this function is running (it is called when a new match is loaded).

However, as I'm sure you've noticed this will just replace the text file with the most recent result each time.

I know that I can use appending to add a new match to each line, but because I'm stubborn I want to add the data within the 'matches' field. Is this possible?

Thanks!

Edit: I just want to add, tonight is my first time playing around with this and I'm pretty new to python too.

That answer was a great help, I've now got some momentum to finish this. Thanks for your help! For reference: final code is as follows.

def write_json(entry):
   current_players = []
   with open("Dota2data.txt","r+") as infile:
      data = json.load(infile)
      for member in entry.players:
         current_players.append(member['account_id'])
      data["matches"].append({"match":entry.match_id, "winner":entry.radiant_win, "players":current_players})
      infile.close()
   with open("Dota2data.txt","r+") as outfile:
      json.dump(data, outfile)
      outfile.close()
   pass

Solution

  • EDIT: before of anything , load the file.

    with open("Dota2data.txt","r+") as outfile:
    

    Sure, first lets load the json file into an object.

    data = json.load(outfile)
    

    Then, add a new property inside 'matches' as a dictionary.

    data['matches'].append({'match':entry.match_id, 'winner':entry.radiant_win, 'players':current_players})
    

    Finally, output the file.

    json.dump(data, outfile)
    

    FULL CODE:

    def write_json(entry):
        with open("Dota2data.txt","r") as infile:
            for member in entry.players:
                current_players = current_players.append(member['account_id'])
            data = json.load(infile)
            infile.close
            data['matches'].append({'match':entry.match_id, 'winner':entry.radiant_win, 'players':current_players})
            with open("Dota2data.txt","w") as outfile:
                json.dump(data, outfile)
                outfile.close()