0

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?

5
  • See this question: stackoverflow.com/questions/1171584/… Commented Sep 21, 2013 at 17:37
  • If I understand correctly, the top answer for that question is to use the json library and use the json.loads function, but as I've mentioned in my question, that is what I'm already using Commented Sep 21, 2013 at 17:45
  • 1
    Can you show the code where you generate the javascript variable json_string? And have you tried logging what self.request.body looks like? I suspect you're not actually sending a json string. Commented Sep 21, 2013 at 17:46
  • @dragonx You were correct, I had stringified what i put into console.log but not what I sent to the ajax function ;) Still, is self.request.body the best way to get the data? Commented Sep 21, 2013 at 18:24
  • yup self.request.body Commented Sep 21, 2013 at 18:37

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.