有没有一种简单的方法来使用python编辑json文件

时间:2014-03-31 01:06:48

标签: python regex json updating

有一些类似的问题可以解决这个问题,但我找不到任何可以满足我需要的东西。

我正在使用的代码如下(python 2.75):(编辑,更新以包含明确的建议:

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

我基本上每次运行此函数时都会在'matches'键中添加一个新的匹配实例(在加载新匹配时调用它)。

但是,我确信您已经注意到,每次都会用最新的结果替换文本文件。

我知道我可以使用追加为每一行添加新匹配,但因为我很顽固,我想在'匹配'字段中添加数据。这可能吗?

谢谢!

编辑:我只想补充一下,今晚是我第一次玩这个游戏,而且我对python也很陌生。

这个答案是一个很大的帮助,我现在有一些动力完成这个。谢谢你的帮助!供参考:最终代码如下。

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

3 个答案:

答案 0 :(得分:1)

编辑:为json.loads将引号更改为“”而不是“”。或者,您可以使用ast.literal_eval()代替。

EDIT2:让我澄清一下,JSON使用双引号进行语法处理,而python可以使用任何一种语法。如果您正在调用json.loads,请为您的JSON使用双引号。如果要使用单引号,请使用ast.literal_eval。确保你import ast

答案 1 :(得分:0)

编辑:在任何事情之前,加载文件。

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

当然,首先让我们将json文件加载到一个对象中。

data = json.load(outfile)

然后,在'matches'内添加一个新属性作为字典。

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

最后,输出文件。

json.dump(data, outfile)

完整代码

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

答案 2 :(得分:0)

def update_file(path, entry):
    with open(path) as infile:
        data = json.load(infile)

    current_players = [member['account_id'] for member in entry.players]
    data["matches"].append({
        "match": entry.match_id,
        "winner": entry.radiant_win, 
        "players": current_players
    })

    with open(path, "w") as outfile:
        json.dump(data, outfile)