如何更改 json 文件中的多个值

问题描述 投票:0回答:1

我想更改 json 文件中的值。 json 文件内容被注释掉。我想单独更改这些值,而必须为每个值单独写入文件。

import json

"""
{
    "keys": {
        "developer": {},
        "personal": {
            "api_key": "1234567890",
            "client_id": "9876543210",
            "client_secret": "ncjegcbcncwkwdcowdch"
        }
    }
}
"""

json_file = "/home/api_keys.json"

with open(json_file) as json_data:
    data = json.load(json_data)

with open(json_file, "w") as jsonFile:
    json.dump(data, jsonFile)

    data["keys"]["personal"]["api_key"] = "9999"

with open(json_file, "w") as jsonFile:
    json.dump(data, jsonFile)   

    data["keys"]["personal"]["client_id"] = "000000000000"

with open(json_file, "w") as jsonFile:
    json.dump(data, jsonFile)

    data["keys"]["personal"]["client_secret"] = "hyfgdjocoduxbxlwowichcnckw"

with open(json_file) as json_data:
    data = json.load(json_data)

    api_key = data["keys"]["personal"]["api_key"]
    client_id = data["keys"]["personal"]["client_id"]
    client_secret = data["keys"]["personal"]["client_secret"]
python json python-3.x
1个回答
0
投票

简答:读取一次,更新 json,然后写入一次。不需要写多次。

import json

"""
{
    "keys": {
        "developer": {},
        "personal": {
            "api_key": "1234567890",
            "client_id": "9876543210",
            "client_secret": "ncjegcbcncwkwdcowdch"
        }
    }
}
"""

json_file = "/home/api_keys.json"

with open(json_file) as json_data:
    data = json.load(json_data)

data["keys"]["personal"]["api_key"] = "9999"
data["keys"]["personal"]["client_id"] = "000000000000"
data["keys"]["personal"]["client_secret"] = "hyfgdjocoduxbxlwowichcnckw"
api_key = data["keys"]["personal"]["api_key"]
client_id = data["keys"]["personal"]["client_id"]
client_secret = data["keys"]["personal"]["client_secret"]

with open(json_file, "w") as jsonFile:
    json.dump(data, jsonFile)
© www.soinside.com 2019 - 2024. All rights reserved.