Jonas Bolin
Jonas Bolin

Reputation: 616

How to receive JSON via jQuery.ajax on Google App Engine

I'm building a Google Forms clone that will create build a form and then store it in the server. The form builder outputs this JSON.stringify format:

{"method":"post","action":"/test","html":[{"input_type":"input_text","caption":"What is your name?"},{"input_type":"radio","caption":"What is the name of your dog?","options":{"benny":"Benny","billy":"Billy","bobby":"Bobby"}}]}

I'm trying to send this to my App Engine backend like this:

$.ajax({
    type: "POST",
    url: save_url,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    data: json_string,
    success: function (e) {
        console.log(e);
    }
});

But how do I "open" this json string on my server, so that I can insert it into my database?

First question: should I use self.request.body to get the data object (the json string), or is there a better way to get it. Right now I have do decode the string to get the proper format.

def post(self):
    form_elements = json.loads(urllib.unquote_plus(self.request.body))
    self.write(form_elements)

Second question: usingjson.loads to parse the json string, I get this error: ValueError: No JSON object could be decoded Why doesn't it understand that it's json?

Upvotes: 0

Views: 1808

Answers (1)

Dave W. Smith
Dave W. Smith

Reputation: 24966

Here's what I do, extracted from working code and stripped down to the essential bits.

  var blob = JSON.stringify(stuff);
  $.ajax('/api/', {
    'type': 'POST',
    'async': false,
    'data': {
      'json': blob,
     },
     'dataType': 'json',
  }).done(function(data) {
    // ...
  }


def post(self):
    blob = self.request.get('json')
    try:
        stuff = json.loads(blob)
    except:
        # ...

I haven't tried using the entirety of request.body.

Upvotes: 4

Related Questions