Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to correctly pass a json object to flask server using jquery ajax

i want to pass a json object which contains nested objects from my client to my server.

on the client side, my data structure looks like this:

var response = {};
response['screening'] = '1';
response['assistance'] = 'wheelchair access';
response['guests'] = {};
response['guests']['1'] = {}
response['guests']['1']['first'] = 'John'
response['guests']['1']['last'] = 'Smith'
response['guests']['2'] = {}
response['guests']['2']['first'] = 'Dave'
response['guests']['2']['last'] = 'Smith'

and my ajax call looks like this:

$.ajax({
  type: "POST",
  url: window.location.pathname,
  data: response
 }).done(function( msg ) {
   alert( "Data Saved: " + msg );
 });

after posting this data to my server, which is run using python flask, i use the request.form object to inspect what was posted from the client. i'd like the data to be structured the same way, however, this is the output on the server:

ImmutableMultiDict([('guests[1][first]', u'John'), ('screening', u'2'), ('guests[2][last]', u'Smith'), ('guests[2][first]', u'Dave'), ('assistance', u'wheelchair access'), ('guests[1][last]', u'Smith')])

as you can see, the response['guests'] object got flattened, and all of its children, such as:

'guests[2][first]'

... are just a strings, not elements of their parent response['guests'].

is there a better way to send this block of data from my client to my server, and maintain its structure properly?

thanks!

like image 282
SeanPlusPlus Avatar asked Apr 04 '13 02:04

SeanPlusPlus


2 Answers

You could send your object as a JSON string:

var data = {
    screening: '1',
    assistance: 'wheelchair access',
    guests: [
        {
            first: 'John',
            last: 'Smith'
        },
        {
            first: 'Dave',
            last: 'Smith'
        }
    ]
};

$.ajax({
    type: 'POST',
    url: window.location.href,
    data: JSON.stringify(response),
    dataType: 'json',
    contentType: 'application/json; charset=utf-8'
}).done(function(msg) {
    alert("Data Saved: " + msg);
});

And then use request.json to access it.

like image 188
Blender Avatar answered Oct 20 '22 05:10

Blender


On the client side, you need to convert that javascript object to a json string. To do so, you can use this:

JSON.stringify(my_object) // This will return a string that you can pass in you ajax request

Then on the server side, you need to convert that object to a python dictionnary using the json module:

import simplejson
my_new_object = simplejson.loads(my_json) // my_json is my_object from the client (previously called my_object)

my_new_object is now a python dictionnary, and you can do whatever you want with it

like image 38
Paco Avatar answered Oct 20 '22 03:10

Paco