简体   繁体   English

如何从 Python 返回值作为 JSON?

[英]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 请求,它期望以 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:在 Python 上,我发送了对 Ajax 请求的响应:

 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.我相信从 python 发送响应作为 JSON 解决了这个问题。 I've nerver used JSON before.我以前用过 JSON。 How can I return response as JSON?如何以 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因为JSON格式一般是这样的

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)如果您使用alert(data) ,您将收到的消息是[object Object]

So use alert(data.file_id);所以使用alert(data.file_id); if you use the example如果你使用这个例子

Encode it using the functions in the json module.使用json模块中的函数对其进行编码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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