How to write a variable in a json file?

Viewed 2628

I searched for a long time but I am not really familiar with python and json and I can't find the answer of my problem. Here is my Python script

import json

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

Here is json the file:

{
    "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
}

I tried .format but we can't use this method with with a dictionary.

With your help I managed to find the answer A big thank you for your speed and your help ! Here is what I did:

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 Answers

You can add data by tranversing through it like a dictionary:

data['key'] = value

Example:

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

A json file is a dictionary, so you can use dict methods with it. Here is the code:

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)
Related