Home > Enterprise >  How to read Json file of list of objects
How to read Json file of list of objects

Time:08-11

I am trying to read a JSON file created from this dictionary below.

players = {
    'Players': [
        Player('P1', 3, 2, 0, 0, 3, 0.3, "sup"),
        Player('P2', 3, 2, 3, 4, 2, 0.5, "adc"),
        Player('P3', 4, 4, 5, 3, 3, 0.7, "mid"),
    ]
}

And the class looks like this.

class Player:
    def __init__(self, id:str="", top:int = 0, jg:int = 0, mid:int = 0, 
                    adc:int = 0, sup:int = 0, win_rate:int = 0, preferred_line:str = "top"):
        self.id = id
        self.position = {"top": top, "jg": jg, "mid": mid, "adc": adc, "sup": sup}
        self.win_rate = win_rate
        self.preferred_line = preferred_line

The JSON file created looks like this.

{"Players": [{"id": "P1", "position": {"top": 3, "jg": 2, "mid": 0, "adc": 0, "sup": 3}, "win_rate": 0.3, "preferred_line": "sup"}, {"id": "P2", "position": {"top": 3, "jg": 2, "mid": 3, "adc": 4, "sup": 2}, "win_rate": 0.5, "preferred_line": "adc"}, {"id": "P3", "position": {"top": 4, "jg": 4, "mid": 5, "adc": 3, "sup": 3}, "win_rate": 0.7, "preferred_line": "mid"}]}

Is there an easy way to convert the file back to its original form?

Thank you in advance!

CodePudding user response:

import json

# read JSON data off file
json_file = r'path/to/file'
with open(json_file) as fhandle:
    data = json.load(fhandle)

# retrive players raw data
players_raw = data.get('Players', [])

# for each player record, unpack the data into Player obj
players = {'Players': [Player(**record) for record in players_raw ]}
  • Related