i tried to edit your code for 11 items like this:
from __future__ import annotations
import json
import contextlib
from typing import Any, Mapping
class Game:
country: str
league: str
date: int
hometeam: str|None
awayteam: str|None
odds1: float|None
oddsX: float|None
odds2: float|None
over: float|None
gline: float|None
under: float|None
@classmethod
def from_json(cls, json_record: Mapping[str, Any]) -> Game:
game = cls()
game.country = json_record["CN"]
game.league = json_record["L"]
game.date = json_record["S"]
game.hometeam = None
game.awayteam = None
game.odds1 = None
game.oddsX = None
game.odds2 = None
game.over = None
game.gline = None
game.under = None
if game_a := json_record.get:
with contextlib.suppress(IndexError):
game.hometeam = game_a.get("O1")
with contextlib.suppress(IndexError):
game.awayteam = game_a.get("O2")
if game_e := json_record.get("E"):
with contextlib.suppress(IndexError):
game.odds1 = game_e[0].get("C")
with contextlib.suppress(IndexError):
game.oddsX = game_e[1].get("C")
with contextlib.suppress(IndexError):
game.odds2 = game_e[2].get("C")
with contextlib.suppress(IndexError):
game.over = game_e[8].get("C")
with contextlib.suppress(IndexError):
game.gline = game_e[8].get("P")
with contextlib.suppress(IndexError):
game.under = game_e[9].get("C")
return game
def __str__(self) -> str:
return ', '.join(
str(item) for item in (
self.country, self.league, self.date, self.hometeam, self.awayteam,
self.odds1, self.oddsX, self.odds2, self.over, self.gline, self.under))
with open("18july.json", encoding="UTF-8") as f:
jsondata = json.load(f)
games = [Game.from_json(game) for game in jsondata["Value"]]
for game in games:
print(game)
but it gave error like this:
Traceback (most recent call last):
File "c:\Users\monst\Downloads\python_files\vcolav.py", line 64, in <module>
games = [Game.from_json(game) for game in jsondata["Value"]]
File "c:\Users\monst\Downloads\python_files\vcolav.py", line 64, in <listcomp>
games = [Game.from_json(game) for game in jsondata["Value"]]
File "c:\Users\monst\Downloads\python_files\vcolav.py", line 36, in from_json
game.hometeam = game_a.get("O1")
AttributeError: 'builtin_function_or_method' object has no attribute 'get'
you know there are 11 items;
Three items (country, league, date) always can be found in json file
but rest 8 items can be missing, so they have to be replaced “None”
Eight items (homeaway, awayteam, odds1, oddsX, odds2, over, gline, under)