Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing JSON array into class instance objects?

Tags:

python

json

I'm trying to parse some data in Python I have some 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
        }
    ]
}

If I wanted to parse the "metros" array into and array of Python class Metro objects, how would I setup the class?

I was thinking:

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

So I want to go through each metro and put the data into a corresponding Metro object and place that object into a Python array of objects...How can I loop through the JSON metros?

like image 354
thebiglebowski11 Avatar asked Feb 21 '13 19:02

thebiglebowski11


1 Answers

If you always get the same keys, you can use ** to easily construct your instances. Making the Metro a namedtuple will simplify your life if you are using it simply to hold values:

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

then simply

import json
data = json.loads('''...''')
metros = [Metro(**k) for k in data["metros"]]
like image 154
nneonneo Avatar answered Sep 19 '22 15:09

nneonneo