我正在尝试将新数据写入现有的 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}}}
最佳答案
- 将文件的 json 数据加载到变量中。
- 更改变量。
- 再次将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/