2011-07-03 91 views
0

我打电话的网址:使用的urllib2和解码使用JSON模块JSON字符串解码错误

url = "http://code.google.com/feeds/issues/p/chromium/issues/full/291?alt=json" 
request = urllib2.Request(query) 
response = urllib2.urlopen(request) 
issue_report = json.loads(response.read()) 

我碰到下面的错误

http://code.google.com/feeds/issues/p/chromium/issues/full/291?alt=json 

ValueError: Invalid control character at: line 1 column 1120 (char 1120) 

我试图检查标题,我得到以下内容:

Content-Type: application/json; charset=UTF-8 
Access-Control-Allow-Origin: * 
Expires: Sun, 03 Jul 2011 17:38:38 GMT 
Date: Sun, 03 Jul 2011 17:38:38 GMT 
Cache-Control: private, max-age=0, must-revalidate, no-transform 
Vary: Accept, X-GData-Authorization, GData-Version 
GData-Version: 1.0 
ETag: W/"CUEGQX47eCl7ImA9WxJaFEw." 
Last-Modified: Tue, 04 Aug 2009 19:20:20 GMT 
X-Content-Type-Options: nosniff 
X-Frame-Options: SAMEORIGIN 
X-XSS-Protection: 1; mode=block 
Server: GSE 
Connection: close 

我还尝试添加的编码参数如下:

issue_report = json.loads(response.read() , encoding = 'UTF-8') 

我仍然会碰到同样的错误。

+0

看起来,你得到了什么不是有效的json编码的字符串。 – hakre

+0

太好了,谢谢!我会照办的。 – Dexter

回答

4

该提要在此处包含来自JPEG中的原始数据; JSON格式不正确,所以这不是你的错。向Google报告错误。

+0

哦!我怀疑人们早些时候也遇到过这样的问题。 http://code.google.com/p/gdata-issues/issues/detail?id=942 – Dexter

2

您可以考虑使用lxml代替,因为JSON格式不正确。这是XPath的支持使得用XML非常直接的工作:

import lxml.etree 
url = 'http://code.google.com/feeds/issues/p/chromium/issues/full/291' 
doc = lxml.etree.parse(url) 
ns = {'issues': 'http://schemas.google.com/projecthosting/issues/2009'} 
issues = doc.xpath('//issues:*', namespaces=ns) 

相当容易操纵的元素,例如从代码中移除的命名空间,转换与dict:

>>> dict((x.tag[len(ns['issues'])+2:], x.text) for x in issues) 
<<<  
{'closedDate': '2009-08-04T19:20:20.000Z', 
'id': '291', 
'label': 'Area-BrowserUI', 
'stars': '13', 
'state': 'closed', 
'status': 'Verified'} 
+0

谢谢,但我一直比较喜欢JSON对象,因为它们很容易转换为字典。 – Dexter

+0

我更喜欢JSON,但有时你没有选择。 – zeekay

+1

目前,我这样做。 :-) – Dexter