python – 将JSON数组解析为对象?

我正在尝试用Python解析一些数据我有一些JSON:

{
    "data sources": [
        "http://www.gcmap.com/"
    ],
    "metros": [
        {
            "code": "SCL",
            "continent": "South America",
            "coordinates": {
                "S": 33,
                "W": 71
            },
            "country": "CL",
            "name": "Santiago",
            "population": 6000000,
            "region": 1,
            "timezone": -4
        },
        {
            "code": "LIM",
            "continent": "South America",
            "coordinates": {
                "S": 12,
                "W": 77
            },
            "country": "PE",
            "name": "Lima",
            "population": 9050000,
            "region": 1,
            "timezone": -5
        }
    ]
}

如果我想将“metros”数组解析为Python类Metro对象的数组,我将如何设置该类?

我刚在想:

class Metro(object):
    def __init__(self):
        self.code = 0
        self.name = ""
        self.country = ""
        self.continent = ""
        self.timezone = ""
        self.coordinates = []
        self.population = 0
        self.region = ""

所以我想浏览每个地铁并将数据放入相应的Metro对象中,并将该对象放入对象的Python数组中……如何循环访问JSON地铁?

如果您始终获得相同的密钥,则可以使用**轻松构建实例.如果您只是使用它来保存值,那么将Metro设置为namedTuple将简化您的生活:

from collections import namedtuple
Metro = namedtuple('Metro', 'code, name, country, continent, timezone, coordinates, population, region')

那么简单

import json
data = json.loads('''...''')
metros = [Metro(**k) for k in data["metros"]]
翻译自:https://stackoverflow.com/questions/15010418/parsing-json-array-into-objects

转载注明原文:python – 将JSON数组解析为对象?