Skip to main content
 首页 » 编程设计

python之如何使用 unicode 从 python 服务解析 JSON语法错误 : Unexpected token u

2025年05月04日62shanyou

我正在从 http://pythond3jsmashup.appspot.com/chart 加载 json使用 Angular js

$http.get('http://pythond3jsmashup.appspot.com/chart'); 

我从如何使用 python ( http://code.tutsplus.com/tutorials/data-visualization-app-using-gae-python-d3js-and-google-bigquery--cms-22175) 将 Google BigQuery 数据作为服务获取的示例中获得此服务。

Angular 在使用 unicode 解析 json 时存在问题。 Angular 有什么办法解决这个问题,还是您必须修改 python 以省略 unicode 字符?

我正在使用 angular 1.3

angular.js:11607 SyntaxError: Unexpected token u I can see it's failing at JSON.parse

从 python 服务返回的数据看起来像这样:

{u'kind': u'bigquery#queryResponse', u'rows': [{u'f': [{u'v': u'brave'}]}, {u'f': [{u'v': u'forfeits'}]}, {u'f': [{u'v': u'holding'}]}, {u'f': [{u'v': u'profession'}]}, {u'f': [{u'v': u'Condemn'}]}, {u'f': [{u'v': u"fear'st"}]}, {u'f': [{u'v': u'answered'}]}, {u'f': [{u'v': u'religion'}]}, {u'f': [{u'v': u"You're"}]}, {u'f': [{u'v': u'deputy'}]}, {u'f': [{u'v': u'heed'}]}, {u'f': [{u'v': u'generation'}]}, {u'f': [{u'v': u'Boldly'}]}, {u'f': [{u'v': u"'"}]}, {u'f': [{u'v': u'told'}]}, {u'f': [{u'v': u'answer'}]}, {u'f': [{u'v': u'regard'}]}, {u'f': [{u'v': u'Touching'}]}, {u'f': [{u'v': u'meet'}]}, {u'f': [{u'v': u"o'er"}]}, {u'f': [{u'v': u'dawn'}]}, {u'f': [{u'v': u'authorities'}]}, {u'f': [{u'v': u'Mended'}]}, {u'f': [{u'v': u'quality'}]}, {u'f': [{u'v': u'lusty'}]}, {u'f': [{u'v': u'forbid'}]}, {u'f': [{u'v': u'instruments'}]}, {u'f': [{u'v': u'A'}]}, {u'f': [{u'v': u'dreadfully'}]}, {u'f': [{u'v': u'accordingly'}]}, {u'f': [{u'v':

请您参考如下方法:

Angular has a problem with the json parse with unicode.

不,问题是服务从字面上返回

{u'kind': u'bigquery#queryResponse', ...}`.  

这不是 JSON。 { 之后的 u 无效(这是错误告诉您的)。简单证明:

> JSON.parse("{u'foo': 'bar'}"); 
Uncaught SyntaxError: Unexpected token u 

无论您做什么,都不会正确创建响应。使用 json.dumps .


鉴于链接教程声称响应是 JSON 这一事实表明它可能不是一个好的教程。

但是,如果您继续按照本教程进行操作,您将看到在 third part 中返回正确的 JSON。 .