0

我正在尝试向我知道使用 python 以 JSON 形式返回数据的 URL 发送 GET 请求。但是,我在第 21 行不断收到 Unicode 解码错误:

Traceback (most recent call last):
  File "MeetupQueryScript.py", line 21, in <module>
    member = json.load(object)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 278, in load
    **kw)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 326, in loads
    return _default_decoder.decode(s)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 366, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 382, in raw_decode
    obj, end = self.scan_once(s, idx)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xe7 in position 20: invalid continuation byte

知道怎么了?

import urllib2
import json

key = '#########'

url = "https://api.meetup.com/2/groups?&sign=true&zip=78705&page=1&key=" + key + "&&sign=true"
object  = urllib2.urlopen(url)
#print [method for method in dir(object) if callable(getattr(object, method))]                                                  
#print object.next()                                                                                                            
groupList = json.load(object)["results"]
groupIDs = []

for group in groupList:
    groupIDs.append(group["id"])

members = []

for id in groupIDs:
    url = "https://api.meetup.com/2/members?&sign=true&group_id=" + str(id) + "&key=" + key
    object = urllib2.urlopen(url)
    member = json.load(object)
    members.append(member)

print members
4

1 回答 1

0

您从聚会中获得的数据是 latin1 编码的(打印 '\xe7'.decode('latin1') 结果为 'ç')。我用你的代码试过了member = json.load(object,encoding='latin1'),它奏效了。

不过,我会推荐requests,因为它有一个更方便的界面:

import requests

url = "https://api.meetup.com/2/groups?&sign=true&zip=78705&page=1&key=" + key + "&&sign=true"
groupList = requests.get(url).json()["results"]
groupIDs = [] 

for group in groupList:
    groupIDs.append(group["id"])

    members = []

for id in groupIDs:
    url = "https://api.meetup.com/2/members?&sign=true&group_id=" + str(id) + "&key=" + key
    member = requests.get(url).json()
    members.append(member)

print members

我支持不要隐藏object在您的代码中的建议。另请查看python 样式指南

于 2013-06-04T06:01:35.357 回答