Unable to parse Yahoo Finance API JSON Data? Code included (Python Flask)
yahoo_api[1]
is a string, use json.loads
to get the json.
import jsonfrom httplib2 import Httpyahoo_api = Http().request('http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20IN%20(%22YHOO%22)&format=json&env=http://datatables.org/alltables.env')yahoo_json = json.loads(yahoo_api[1])change = yahoo_json['query']['results']['quote']['Change']symbol = yahoo_json['query']['results']['quote']['symbol']
Anthoer way is using requests
, no worry about the json, it is esay to use.
import requestsr = requests.get('http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20IN%20%28%22YHOO%22%29&format=json&env=http://datatables.org/alltables.env')change = r.json()['query']['results']['quote']['Change']symbol = r.json()['query']['results']['quote']['symbol']
I'd think you might have forgotten to take the second part of the tuple (the content), although that seemed unlikely as you do do this for the return statement. Or maybe you forgot the UTF-8 decode?
import jsonimport pprintfrom httplib2 import Httphttp = Http()url = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20IN%20(%22YHOO%22)&format=json&env=http://datatables.org/alltables.env"yahoo_api = http.request(url)result = json.loads(yahoo_api[1].decode('utf-8'))pprint.pprint(result)