I'm trying to return data to Django model, from Overpass API JSON data after downloaded
"elements": [
{
"type": "node",
"id": 662934404,
"lat": 35.572157,
"lon": 45.3898839,
"tags": {
"addr:postcode": "46001",
"name": "City Center",
"name:en": "City Center Mall",
"name:ku": "City Center Mall",
"shop": "mall",
"website": "http://www.citycentersul.com"
}
},
{
"type": "node",
"id": 2413990402,
"lat": 35.5014386,
"lon": 45.4457576,
"tags": {
"addr:city": "sulaymaniyah",
"designation": "ASSAN",
"name": "ASSAN STEEL CO.",
"opening_hours": "3 min",
"shop": "doityourself",
"source": "ASSAN Steel Company General Trading Co, Ltd"
},
{
"type": "node",
"id": 2414374708,
"lat": 35.506121,
"lon": 45.4417229,
"tags": {
"addr:city": "sulaymaniyah",
"name:ku": "ASSAN Steel Company General Trading Co, Ltd",
"shop": "doityourself",
}
},
but some of the data dosent have both of them together name , name:ku ,name:en
so what should i do if name is none then return name:ku , if its exists then name:en
i've tried this but doesnt work
with open('data.json') as datafile:
objects = json.load(datafile)
for obj in objects['elements']:
try:
objType = obj['type']
if objType == 'node':
tags = obj['tags']
name = tags.get('name')
if not name:
name = tags.get('name:en')
elif not name:
name = tags.get('name:ku')
elif not name:
name = tags.get('name:ar')
else:
name = tags.get('shop','no-name')
is there something else I've missed? thanks for helping
You could loop over all possible keys and stop after a value was detected:
with open('data.json') as datafile:
objects = json.load(datafile)
for obj in objects['elements']:
objType = obj['type']
if objType == 'node':
tags = obj['tags']
name = None
for nameId in ('name', 'name:en', 'name:ku', 'name:ar'):
if nameId in tags:
name = tags[name]
break # stop looping, we got a name value
# Set default if no key was found
if not name:
name = tags.get('shop','no-name')