I’m trying to parse some data in Python I have some JSON:
JavaScript
x
34
34
1
{
2
"data sources": [
3
"http://www.gcmap.com/"
4
],
5
"metros": [
6
{
7
"code": "SCL",
8
"continent": "South America",
9
"coordinates": {
10
"S": 33,
11
"W": 71
12
},
13
"country": "CL",
14
"name": "Santiago",
15
"population": 6000000,
16
"region": 1,
17
"timezone": -4
18
},
19
{
20
"code": "LIM",
21
"continent": "South America",
22
"coordinates": {
23
"S": 12,
24
"W": 77
25
},
26
"country": "PE",
27
"name": "Lima",
28
"population": 9050000,
29
"region": 1,
30
"timezone": -5
31
}
32
]
33
}
34
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:
JavaScript
1
11
11
1
class Metro(object):
2
def __init__(self):
3
self.code = 0
4
self.name = ""
5
self.country = ""
6
self.continent = ""
7
self.timezone = ""
8
self.coordinates = []
9
self.population = 0
10
self.region = ""
11
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:
JavaScript
1
4
1
from collections import namedtuple
2
Metro = namedtuple('Metro', 'code, name, country, continent, timezone, coordinates,
3
population, region')
4
then simply
JavaScript
1
4
1
import json
2
data = json.loads('''...''')
3
metros = [Metro(**k) for k in data["metros"]]
4