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?
Advertisement
Answer
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"]]