2016-03-23 34 views
0

Web sitesinden veri istemek için bir API kullanıyorum. Veriler here bulunabilir ve JSON Viewer içine yapıştırılabilir. Benim kodum, geri döndüğü hata ile birlikte. Bunun hızlı bir çözüm olduğunu tahmin ediyorum, kısmen ilk defa bu urllib'i kullandığım gerçeğini yansıtır.TypeError ayrıştırma JSON obj from urllib ipython

import pandas as pd 
import urllib 
import json 

api_key = '79bf8eb2ded72751cc7cda5fc625a7a7' 
url = 'http://maplight.org/services_open_api/map.bill_list_v1.json?apikey=79bf8eb2ded72751cc7cda5fc625a7a7&jurisdiction=us&session=110&include_organizations=1&has_organizations=1' 

json_obj = urllib.request.urlopen(url) 

data = json.load(json_obj) 

--------------------------------------------------------------------------- 
TypeError         Traceback (most recent call last) 
<ipython-input-21-85ab9af07320> in <module>() 
     8 json_obj = urllib.request.urlopen(url) 
     9 
---> 10 data = json.load(json_obj) 

/home/jayaramdas/anaconda3/lib/python3.5/json/__init__.py in load(fp, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw) 
    266   cls=cls, object_hook=object_hook, 
    267   parse_float=parse_float, parse_int=parse_int, 
--> 268   parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw) 
    269 
    270 

/home/jayaramdas/anaconda3/lib/python3.5/json/__init__.py in loads(s, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw) 
    310  if not isinstance(s, str): 
    311   raise TypeError('the JSON object must be str, not {!r}'.format(
--> 312        s.__class__.__name__)) 
    313  if s.startswith(u'\ufeff'): 
    314   raise JSONDecodeError("Unexpected UTF-8 BOM (decode using utf-8-sig)", 

TypeError: the JSON object must be str, not 'bytes' 

Her türlü öneri, yorum veya sorularınız için teşekkür ederiz. genellikle döndürülen nesneden bayt .read ve sonra .decode ve uygun codec'i kullanarak bir dizeye bu bayt dönüştürmek gerekir böylece

+1

görünüyor. Json.load (json_obj.decode ('utf-8')) 'yi denediniz mi? – mgilson

+0

Öneriniz için teşekkür ederiz! Sadece önerinizi denedim. Aşağıdaki hatayı aldım: AttributeError: 'HTTPResponse' nesnesinin 'encode' özelliği yok –

+1

Oops ... json.loads (json_obj.read(). Decode ('utf-8')) 'belki? – mgilson

cevap

2

json.load, kodlama tahmin olmayacaktır. ör .:

official documentation içinde bunun bir örneğidir vardır
data = json.loads(json_obj.read().decode('utf-8')) 

.

Özellikle, diyor ki: o str` değil `bytes`` istediği gibi

Note that urlopen returns a bytes object. This is because there is no way for urlopen to automatically determine the encoding of the byte stream it receives from the http server. In general, a program will decode the returned bytes object to string once it determines or guesses the appropriate encoding.