【问题标题】:JSON string decoding errorJSON字符串解码错误
【发布时间】:2011-07-03 17:45:48
【问题描述】:

我正在调用网址:

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

使用 urllib2 并使用 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())

我遇到以下错误:

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')

我仍然遇到同样的错误。

【问题讨论】:

  • 看起来你得到的不是一个有效的json编码字符串。

标签: python urllib2 json


【解决方案1】:

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

【讨论】:

【解决方案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((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'}

【讨论】:

  • 谢谢,但我总是更喜欢 JSON 对象,因为它们很容易转换成字典。
  • 我也更喜欢 JSON,但有时你别无选择。
猜你喜欢
  • 2013-05-10
  • 2016-11-14
  • 2019-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-09-22
  • 1970-01-01
相关资源
最近更新 更多