2012-03-20 71 views
2

我创建了一个表单,当我点击提交按钮时,我将3值赋给一个javascript dict并发送给python脚本来处理,但是我的web浏览器告诉我一个错误!在python输出中删除`u`字符

从Json的错误:{u'food ':90,u'cargo':70,u'fuel':50}的SyntaxError

controller.js

function customiseCtrl($xhr){ 
var self = this; 

checkPoint(); 
this.process = function(){ 
    if (checkPoint()){ 

     var newPlayer = {"fuel":value, "food":value2, "cargo":value3 }; 

     $xhr('POST', '/process', newPlayer, function (code, response) { 
      self.x = response; 

     }); 
    } 
}; 


} 

/过程 - > Python脚本(我想读的“信息”的信息,并将其写入到谷歌应用程序引擎。

def post(self): 
user = users.get_current_user() 
player = Player(); 

info = json.loads(self.request.body) 
player.fuel = info.fuel 
self.response.out.write(info) 
+4

Python的'repr'(这里隐式调用)不是为了产生JSON而设计的。 – robert 2012-03-20 16:45:48

+1

[Removing u in list](http://stackoverflow.com/questions/9773121/removing-u-in-list) – geoffspear 2012-03-20 17:24:32

回答

8

打印Python字典在很多情况下不会生成有效的JSON。你想要json模块:

import json 

# ... snip ... 

self.response.out.write(json.dumps(info)) 
# or 
json.dump(info, self.response.out) 
+0

'json.dump(info,self.response)'也可以工作,如果它是一个类似文件的对象 – ThiefMaster 2012-03-20 16:47:56

+0

谢谢,补充。两者之间可能存在性能差异? – nrabinowitz 2012-03-20 16:51:17

+1

对于复杂或大型的数据集,是的,使用'json.dump'会更高效。 – 2012-03-20 16:56:00

3

的问题不是在JavaScript(按你的原题),它在输出JSON,你需要输出格式正确的JSON,如果它看起来像{u'food': 90, u'cargo': 70, u'fuel': 50},self.response.out.write(info)没有做。 (jsonlint.com是非常方便的验证JSON文本。)

我没有太大的蟒蛇头(其实,我不是蟒蛇头的话),但我想你想更换

self.response.out.write(info) 

json.dump(info, self.response) 

..或者类似(上述假定self.response“......一个.write() - 支持类文件对象...”),基于this reference

+0

我想为了像你一样使用'self.response.out',你需要'json.dump',它写入类文件对象,而不是'json.dumps',它返回一个字符串。 – nrabinowitz 2012-03-20 16:48:38

+0

@nrabinowitz:谢谢,修正。 – 2012-03-20 16:49:31

+0

@downvoter:我会感兴趣的是为什么你找到这个答案“没有用”(使用downvote按钮上的工具提示的措词)。 – 2012-03-20 17:29:05