2

I create a form and when I click the submit button, I assign the 3 value into a javascript dict and send it over to a python script to process however My web browser tell me a error!

from Json error: {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;

        });
    }
};


}

/process --> python script (I am trying to read the information of "info" and write it into the Google app engine.

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)
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
Brian Li
  • 573
  • 2
  • 7
  • 10
  • 4
    Python's `repr` (which is being implicitly called here) isn't designed to produce JSON. – robert Mar 20 '12 at 16:45
  • 1
    possible duplicate of [Removing u in list](http://stackoverflow.com/questions/9773121/removing-u-in-list) – Wooble Mar 20 '12 at 17:24

2 Answers2

8

Printing a Python dict will in many cases not generate valid JSON. You want the json module:

import json

# ... snip ...

self.response.out.write(json.dumps(info))
# or
json.dump(info, self.response.out)
nrabinowitz
  • 55,314
  • 10
  • 149
  • 165
3

The problem isn't in the JavaScript (per your original title), it's in the output of the JSON. You need to output properly-formatted JSON, which if it looks like {u'food': 90, u'cargo': 70, u'fuel': 50}, self.response.out.write(info) isn't doing. (jsonlint.com is handy for validating JSON text.)

I'm not much of a python-head (actually, I'm not a python-head at all), but I think you want to replace

self.response.out.write(info)

with

json.dump(info, self.response)

..or similar (the above assumes that self.response is a "...a .write()-supporting file-like object..."), based on this reference.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • I think in order to use `self.response.out` like you do, you need `json.dump`, which writes to a file-like object, not `json.dumps`, which returns a string. – nrabinowitz Mar 20 '12 at 16:48
  • @nrabinowitz: Actually, when using `.write()` using the `dumps()` method is perfectly fine. But of course using `dump()` is a little bit faster since the json can be written directly to the object without creating a string containing everything. However, with `self.response` probably being a stringio or similar object it won't matter much. – ThiefMaster Mar 20 '12 at 18:30