我对JSON文件一无所知,我试图使用Python中的if结构的循环来修改其中的一些值。
我认为这将是一个简单的任务,但因为我不知道任何关于JSON文件,我有问题访问值开始的条件。
Json文件:
{
"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
}
}
]
}
字符串
“gender”属性将其值更改为1或2,1表示女性,2表示男性。如果“gender”为1,我想将“pregnant”属性从false更改为true,false表示未怀孕,true表示怀孕。
功能说明:
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()
型
我还想修改“装备装备”和“装备武器”属性。它们对应于角色装备的装备和武器,根据每个武器的ID而变化。
如果“equipedOutfit”的id与“JobinsonsJersey”不同,我希望它成为“JobinsonsJersey”。
功能说明:
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()
型
如果“equipedWeapon”的id与“PlasmaThrower_DragonsMaw”不同,我希望它成为“PlasmaThrower_DragonsMaw”
功能说明:
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()
型
对于所有函数,我都得到Traceback错误,因为我真的不知道如何访问属性。
有人可以帮助我pls!
1条答案
按热度按时间qmb5sa221#
你可以使用这个例子来加载Json数据到Python对象并更改各种属性:
字符串
创建此
data_out.json
:型