Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to read Json file of list of objects

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{"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!

>Solution :

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 ]}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading