简体   繁体   中英

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?

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

Encode it using the functions in the json module.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM