Reputation: 57
I am using this code bit:
from flask import Flask, jsonify, abort, request
from datetime import datetime
import json
import cx_Oracle
import requests
/*Some other code bits*/
longitude = 0.0
latitude = 0.0
try:
params = {
'action': 'query',
'country': 'Hungary',
'city': 'Budapest',
'format' : 'json',
}
res = requests.get('http://nominatim.openstreetmap.org/search.php', params=params)
page = res.json()
latitude = page['lat']
longitude =page['lon']
except:
pass
return jsonify(name=result[0],address=result[1],phone=result[2],income=result[3],Latitude = latitude, Longitude=longitude)
And I am trying to get the latitude and logitude from this link that is in JSON format: http://nominatim.openstreetmap.org/search.php?action=query&format=json&city=Budapest&country=Hungary
name=result[0],address=result[1],phone=result[2],income=result[3] are fine, and work well, however, I must be doing something wrong becouse Latitude and Longitude remains 0.0. If I remove the intialization from line 1, and 2, then I get and error that
UnboundLocalError: local variable 'latitude' referenced before assignment
probably becouse it runs into some kind of error within the try block.
I am sorry for this easy question I am very new to python and JSON.
Upvotes: 0
Views: 64
Reputation: 16147
The dictionary is contained within a list, which very confusing to beginners. If you see []'s in the response, you have to use a numerical index to reference the content inside of those brackets. Then you can reference by keyword for the dict inside. Use requests to fetch JSON.
import requests
r = requests.get('http://nominatim.openstreetmap.org/search.php?action=query&format=json&city=Budapest&country=Hungary').json()
print(r[0]['lon'])
print(r[0]['lat'])
Output: 19.0404707 47.4983815
Process finished with exit code 0
Upvotes: 1