2016-03-23 5 views
0

ウェブサイトからデータを要求するAPIを使用しています。データはhereであり、JSON Viewerに貼り付けられています。私のコードとそれが戻ってくるエラーは以下の通りです。私はこれが迅速な修正だと推測しています。これは、これが初めてurllibを使用しているという事実を部分的に反映しています。urllibからJSON objを解析するエラータイプ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' 

いずれかの提案、コメント、またはさらなる質問があります。あなたは通常、返されたオブジェクトからバイトを.readし、その後.decodeと適切なコーデックを使用して文字列にそれらのバイトを変換する必要があるので、

+1

それは 'str'、ない' bytes'望んでいるように見えます。 'json.load(json_obj.decode( 'utf-8'))'を試しましたか? – mgilson

+0

ありがとうございました!私はちょうどあなたの提案を試みた。 'AttributeError: 'HTTPResponse'オブジェクトに 'エンコード'属性がありません。 –

+1

おっと...' json.loads(json_obj.read()。decode( 'utf-8')) 'maybe? – mgilson

答えて

2

json.loadは、エンコーディングを推測しません。例:

data = json.loads(json_obj.read().decode('utf-8')) 

official documentationに例があります。

具体的には、それは言う:

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.