python - 更改 json 值并创建新值

标签 python json

我正在尝试将新数据写入现有的 json,但没有成功。这是我当前的 json 文件 dat.dat:

{"users": {"tryhard_cupcake": {"Points": 0, "Time Joined": 9938}}}

以及我如何解析它:

def updateUsers(chan):
    j = urllib2.urlopen('http://tmi.twitch.tv/group/user/' + chan + '/chatters')
    j_obj = json.load(j)
    with open('dat.dat', 'r+w') as data_file:
            data = json.load(data_file)
        for dat in data['users']:
            if dat in j_obj['chatters']['moderators']:
                points=data['users'][dat]['Points']
                json.dump(points + 50, data_file)

updateUsers('tryhard_cupcake')

我本来希望为用户添加 50 分,但它只是在文件末尾附加了 50 分。输出是这样的:

{"users": {"tryhard_cupcake": {"Points": 0, "Time Joined": 9938}}}
50

如何向用户添加新数据并对其进行修改?我期待这个结果:

{"users": {"tryhard_cupcake": {"Points": 50, "Time Joined": 9938}}}

最佳答案

  1. 将文件的 json 数据加载到变量中。
  2. 更改变量。
  3. 再次将json变量写入文件中。

像这样更改您的updateUsers:

def updateUsers(chan):
    j = urllib2.urlopen('http://tmi.twitch.tv/group/user/' + chan + '/chatters')
    j_obj = json.load(j)
    with open('dat.dat') as data_file:
            data = json.load(data_file)
        for dat in data['users']:
            if dat in j_obj['chatters']['moderators']:
                data['users'][dat]['Points'] += 50
    # write to file
    with open('dat.dat', 'w') as out_file:
        json.dump(data, out_file)

关于python - 更改 json 值并创建新值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33638916/

相关文章:

python - 带有 Python : How to optimize my implementation? 的 TCP 服务器

jquery - JSON多类别过滤器

javascript - 使用 Javascript 从 Json 中的子元素创建新键

json - 有没有办法在严格的 JSON 模式下运行 MongoDB shell(或 tojson 方法)?

javascript - 使用 base64 编码数据更新 SQL 查询

android - 将 JSON 解析为 ListView 友好的输出

python - 单列中的 Pandas 天数

python - 单击不会让我传递多个文件,尽管它应该是可能的

Python Pandas : Read specific columns from cdv, 然后重新排序

python - 如何检查是否可以在 Python 对象中设置(修补)属性