简体   繁体   English

如何读取对象列表的 Json 文件

[英]How to read Json file of list of objects

I am trying to read a JSON file created from this dictionary below.我正在尝试阅读从下面的字典创建的 JSON 文件。

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 看起来像这样。

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.创建的 JSON 文件如下所示。

{"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!先感谢您!

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 ]}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM