简体   繁体   English

如何将键:值对添加到简单的 JSON 文件

[英]How can I add key: value pair to simple JSON file

JSON JSON

{
    "user1": "password1",
    "user2": "password2"
}

Code代码

So let's say I have one new user, user3 I'll store his password and username into two different variables所以假设我有一个新用户 user3 我会将他的密码和用户名存储到两个不同的变量中

username = "user3"
password = "password3"

Output Goal Output 目标

I'd like my JSON file to finally look like this:我希望我的 JSON 文件最终看起来像这样:

{
    "user1": "password1",
    "user2": "password2",
    "user3": "password3
}

Just parse you json into a dict, add the key/value pair and dump it back to a json string:只需将 json 解析为 dict,添加键/值对并将其转储回 json 字符串:

import json

j = '''{
    "user1": "password1",
    "user2": "password2"
}'''

username = "user3"
password = "password3"

my_dict = json.loads(j)
my_dict[username] = password

json.dumps(my_dict)
# '{"user1": "password1", "user2": "password2", "user3": "password3"}'

If you starting from a file, it's basically the same — just open the file and use load() and dump() .如果你从一个文件开始,它基本上是一样的——只要打开文件并使用load()dump() Something like:就像是:

import json

path = "/path/to/file.txt"
outpath = "/path/to/output_file.txt"

username = "user3"
password = "password3"

with open(path) as json_file:
    my_dict = json.load(json_file)

my_dict[username] = password

with open(outpath, 'w') as json_file:
    json.dump(my_dict, json_file)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM