Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return value from Python as JSON?

I sending ajax request from a jQuery file like below, which expects response in JSON.

jQuery.ajax({
    url: '/Control/getImageDetails?file_id='+currentId,
    type: 'GET',
    contentType: 'application/json',
    success: function (data){
        alert(data);
    }
 });
});

On Python I sent response to the Ajax request as such:

 record = meta.Session.query(model.BannerImg).get(fid)
 return_info = [record.file_id, record.filename, record.links_to]
 return result_info

This returns paramaters in plain text making it impossinle to read as different values. i believe sending off response from python as JSON solve this issue. I've nerver used JSON before. How can I return response as JSON?

like image 631
Sushan Ghimire Avatar asked Jul 04 '12 16:07

Sushan Ghimire


Video Answer


2 Answers

return json.dumps(return_info)

main problem is

return_info = [record.file_id, record.filename, record.links_to]

because JSON format is generally like

Example:

json.dumps({'file_id': record.file_id, 'filename': record.filename , 'links_to' : record.links_to})

and the message you are going to receive is [object Object] if you use alert(data)

So use alert(data.file_id); if you use the example

like image 83
iraycd Avatar answered Sep 23 '22 07:09

iraycd


Encode it using the functions in the json module.

like image 27
Ignacio Vazquez-Abrams Avatar answered Sep 20 '22 07:09

Ignacio Vazquez-Abrams