[英]Python - append data to a json file
I have the following data in my c.json
file: 我的
c.json
文件中包含以下数据:
{
"192.168.0.129": {
"username": "me",
"streaming": "Spotify",
"name": "John",
"email": "john@gmail.com"
}
}
and this other data that I want to append it to: 以及我要附加到的其他数据:
new_data = {'next_songs': ['song1', 'song2']}
for that purpose I'm doing this: 为此,我正在这样做:
with open('c.json', 'r') as json_data:
data = json.load(json_data)
data.update(new_data)
with open('c.json', 'w') as json_data:
json.dump(data, json_data, indent=4)
this works, but no quite, because I get: 这行得通,但不完全有效,因为我得到了:
{
"next_songs": [
"song1",
"song2"
],
"192.168.0.129": {
"username": "me",
"streaming": "Spotify",
"name": "John",
"email": "john@gmail.com"
}
}
and I want appended data to be a value under the key "192.168.0.129"
, like so: 我希望附加的数据成为键
"192.168.0.129"
下的值,如下所示:
{
"192.168.0.129": {
"username": "me",
"streaming": "Spotify",
"name": "John",
"email": "john@gmail.com"
"new_data": ["song1", "song2"],
}
}
how do I achieve this? 我该如何实现?
Only a certain dict property "192.168.0.129"
(which is the inner dict) should be updated, not the whole main dict: 仅应更新某些字典属性
"192.168.0.129"
(这是内部字典),而不要更新整个主要字典:
...
data["192.168.0.129"].update(new_data)
It looks like you may be updating the wrong dictionary 看来您可能正在更新错误的字典
data.update(new_data)
should be data["192.168.0.129"].update(new_data)
data.update(new_data)
应该是data["192.168.0.129"].update(new_data)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.