我正在解析一个JSON文件。作为我对文件执行的操作的一部分,我需要从键"homeAbbr"
中值为"ORE"
的任何元素的100中减去yardLine
键。不管代码是更新原始的yardLine
键的值还是用修改后的值创建一个新的yardLineReal
键—我两种方法都试过了,但新键更容易创建,这样就不会无限循环,这似乎是合乎逻辑的。下面是JSON的两个元素的示例-每个元素都有相同的键:
{
"gameId": "400935253",
"year": 2017,
"week": 1,
"homeId": "2483",
"homeTeam": "Oregon",
"homeAbbr": "ORE",
"awayId": "253",
"awayTeam": "Southern Utah",
"awayAbbr": "SUU",
"driveIndex": "2",
"playIndex": "1",
"offenseId": "2483",
"offenseTeam": "Oregon",
"offenseAbbr": "ORE",
"defenseId": "253",
"defenseTeam": "Southern Utah",
"defenseAbbr": "SUU",
"homeScore": 7,
"awayScore": 7,
"isScore": false,
"quarter": 1,
"clock": "11:39",
"type": "Rush",
"down": 1,
"distance": 10,
"yardLine": 26,
"yardsGained": 14,
"endYardLine": 40,
"description": "Royce Freeman run for 14 yds to the Oregn 40 for a 1ST down"
},
{
"gameId": "400935253",
"year": 2017,
"week": 1,
"homeId": "2483",
"homeTeam": "Oregon",
"homeAbbr": "ORE",
"awayId": "253",
"awayTeam": "Southern Utah",
"awayAbbr": "SUU",
"driveIndex": "2",
"playIndex": "2",
"offenseId": "2483",
"offenseTeam": "Oregon",
"offenseAbbr": "ORE",
"defenseId": "253",
"defenseTeam": "Southern Utah",
"defenseAbbr": "SUU",
"homeScore": 7,
"awayScore": 7,
"isScore": false,
"quarter": 1,
"clock": "11:39",
"type": "Rush",
"down": 1,
"distance": 10,
"yardLine": 40,
"yardsGained": 3,
"endYardLine": 43,
"description": "Royce Freeman run for 3 yds to the Oregn 43"
}
下面是我提出的非函数代码,试图用编辑后的值创建一个名为yardLineReal
的新键(我直接在yardLine
中编辑值的非函数代码只在第8行中的键的名称不同):
import json
with open ('data.json', 'r') as data_file:
data = json.load(data_file)
for element in data:
if 'ORE' in element["homeAbbr"]:
data[yardLineReal] = 100 - data[yardLine]
with open('data.json', 'w') as data_file:
data = json.dump(data, data_file)
我不相信代码会像编写的那样调用与yardLine
关联的值。我想问题归根结底是,有没有办法引用这个值?你知道吗
谢谢:)
你可以只更新
element
本身。这将导致data
也被更新:当然,您可以调用与“yardLine”相关联的值
这个代码是工作!你知道吗
结果:
一旦将JSON文件加载到Python中,它就变成了一个字典。你可以这样迭代:
我不确定你到底想做什么,但这应该能帮助你开始。你知道吗
相关问题 更多 >
编程相关推荐