如何在json文件中写入变量?

时间:2020-04-07 09:24:11

标签: python json variables

我搜索了很长时间,但是我对python和json并不是很熟悉,并且找不到我的问题的答案。 这是我的Python脚本

导入json

jsonFile = open("config.json", "r")
data = json.load(jsonFile)
data.format(friendly, teaching, leader, target)
print(data)

这是json文件:

{
    "commend": {
        "friendly": {},
        "teaching": {},
        "leader": {}
    },
    "account": {
        "username": "",
        "password": "",
        "sharedSecret": ""
    },
    "proxy": {
        "enabled": false,
        "file": "proxies.txt",
        "switchProxyEveryXaccounts": 5
    },
    "type": "COMMEND",
    "method": "SERVER",
    "target": "https://steamcommunity.com/id/{}",
    "perChunk": 20,
    "betweenChunks": 300000,
    "cooldown": 28800000,
    "steamWebAPIKey": "{}",
    "disableUpdateCheck": false
}

我尝试过.format,但是我们不能将这种方法与字典一起使用。

在您的帮助下,我设法找到了答案。非常感谢您的速度和帮助!这是我所做的:

import json

    jsonFile = open("config.json", "r")
    data = json.load(jsonFile)
    (data['commend']['friendly']) = nbfriendly
    (data['commend']['teaching']) = nbteaching
    (data['commend']['leader']) = nbleader
    print(data)
    print(data)

2 个答案:

答案 0 :(得分:1)

您可以像字典一样遍历数据来添加数据:

data['key'] = value

示例:

dic["commend"]["friendly"]={'a':1}

答案 1 :(得分:0)

json文件是一个字典,因此您可以使用dict方法。这是代码:

import json

with open("config.json", "r") as json_file:
    data = json.load(json_file)
    # Let's say you want to add the string "Hello, World!" to the "password" key
    data["account"]["password"] += "Hello, World!"
    # Or you can use this way to overwrite anything already written inside the key
    data["account"]["password"] = "Hello, World!"
print(data)