Search code examples
pythonjsonloopsif-statementtraceback

How to modify the value of an attribute according to a condition in a JSON file using python


I don't know anything about JSON files and I'm trying to use a loop with an if structure in python to modify some values ​​in it.

I thought it would be an easy task but as I don't know anything about JSON files I'm having problems accessing the values ​​to start the conditions.

Json File:

{
    "dwellers": [
        {
            "serializeId": 1,
            "name": "Kathleen",
            "lastName": "Hall",
            "gender": 1,
            "pregnant": false,
            "babyReady": false,
            "equipedOutfit": {
                "id": "jumpsuit",
                "type": "Outfit",
                "hasBeenAssigned": false,
                "hasRandonWeaponBeenAssigned": false
            },
            "equipedWeapon": {
                "id": "Fist",
                "type": "Weapon",
                "hasBeenAssigned": false,
                "hasRandonWeaponBeenAssigned": false
            }
        },

        {
            "serializeId": 2,
            "name": "MS",
            "lastName": "1",
            "gender": 2,
            "pregnant": false,
            "equipedOutfit": {
                "id": "JobinsonsJersey",
                "type": "Outfit",
                "hasBeenAssigned": false,
                "hasRandonWeaponBeenAssigned": false
            },
            "equipedWeapon": {
                "id": "PlasmaThrower_DragonsMaw",
                "type": "Weapon",
                "hasBeenAssigned": false,
                "hasRandonWeaponBeenAssigned": false
            }
        },

        {
            "serializeId": 3,
            "name": "WSLD",
            "lastName": "1",
            "gender": 2,
            "pregnant": false,
            "babyReady": false,
            "equipedOutfit": {
                "id": "JobinsonsJersey",
                "type": "Outfit",
                "hasBeenAssigned": false,
                "hasRandonWeaponBeenAssigned": false
            },
            "equipedWeapon": {
                "id": "PlasmaThrower_DragonsMaw",
                "type": "Weapon",
                "hasBeenAssigned": false,
                "hasRandonWeaponBeenAssigned": false
            }
        }
    ]
}

The "gender" attribute changes its value to 1 or 2, with 1 being female and 2 being male. If "gender" is 1, I want to change the "pregnant" attribute from false to true, with false being not pregnant and true being pregnant.

Function:

def gimmeChild():
    with open('./mindweller.json', 'r') as file:
        dwellers = json.load(file)
    
    for object in dwellers:
        if object["pregnant"] == "false":
            object["pregnant"] == "true"
            break
        else:
            print("erro")
            
    dwellers.close()

I also want to modify the "equipedOutfit" and "equipedWeapon" attributes. They correspond to which outfit and which weapon the character has equipped, varying according to the ID of each weapon.

If the id of "equipedOutfit" is different from "JobinsonsJersey" I want it to become "JobinsonsJersey".

Function:

def gimmeOutfit():
    with open('./mindweller.json', 'r') as file:
        dwellers = json.load(file)
        
    for object in dwellers:
        if object["equipedOutfit"]["id"] != "JobinsonsJersey":
            object["equipedOutfit"]["id"] = "JobinsonsJersey"
            break
        else:
            print("erro")
            
    dwellers.close()

And if the id of "equipedWeapon" is different from "PlasmaThrower_DragonsMaw" I want it to become "PlasmaThrower_DragonsMaw"

Function:

def gimmeGun():
    with open('./mindweller.json', 'r') as file:
        dwellers = json.load(file)
    
    for object in dwellers:
        if object["equipedWeapon"]["id"] != "PlasmaThrower_DragonsMaw":
            object["equipedWeapon"]["id"] = "PlasmaThrower_DragonsMaw"
            break
        else:
            print("erro")
            
    dwellers.close()

For all functions I get Traceback error because because I don't really know how to access the attributes.

Someone can help me pls!?


Solution

  • You can use this example how to load the Json data to Python object and change the various attributes:

    import json
    
    with open("data.json", "r") as f_in:
        data = json.load(f_in)
    
    for d in data["dwellers"]:
        # 1. change to "pregnant"
        if d["gender"] == 1:
            d["pregnant"] = True
    
        # 2. equipedOutfit -> JobinsonsJersey
        d["equipedOutfit"]["id"] = "JobinsonsJersey"
    
        # 3. equipedWeapon -> PlasmaThrower_DragonsMaw
        d["equipedWeapon"]["id"] = "PlasmaThrower_DragonsMaw"
    
    with open("data_out.json", "w") as f_out:
        json.dump(data, f_out, indent=4)
    

    Creates this data_out.json:

    {
        "dwellers": [
            {
                "serializeId": 1,
                "name": "Kathleen",
                "lastName": "Hall",
                "gender": 1,
                "pregnant": true,
                "babyReady": false,
                "equipedOutfit": {
                    "id": "JobinsonsJersey",
                    "type": "Outfit",
                    "hasBeenAssigned": false,
                    "hasRandonWeaponBeenAssigned": false
                },
                "equipedWeapon": {
                    "id": "PlasmaThrower_DragonsMaw",
                    "type": "Weapon",
                    "hasBeenAssigned": false,
                    "hasRandonWeaponBeenAssigned": false
                }
            },
            {
                "serializeId": 2,
                "name": "MS",
                "lastName": "1",
                "gender": 2,
                "pregnant": false,
                "equipedOutfit": {
                    "id": "JobinsonsJersey",
                    "type": "Outfit",
                    "hasBeenAssigned": false,
                    "hasRandonWeaponBeenAssigned": false
                },
                "equipedWeapon": {
                    "id": "PlasmaThrower_DragonsMaw",
                    "type": "Weapon",
                    "hasBeenAssigned": false,
                    "hasRandonWeaponBeenAssigned": false
                }
            },
            {
                "serializeId": 3,
                "name": "WSLD",
                "lastName": "1",
                "gender": 2,
                "pregnant": false,
                "babyReady": false,
                "equipedOutfit": {
                    "id": "JobinsonsJersey",
                    "type": "Outfit",
                    "hasBeenAssigned": false,
                    "hasRandonWeaponBeenAssigned": false
                },
                "equipedWeapon": {
                    "id": "PlasmaThrower_DragonsMaw",
                    "type": "Weapon",
                    "hasBeenAssigned": false,
                    "hasRandonWeaponBeenAssigned": false
                }
            }
        ]
    }