【问题标题】:Retrive data from jquery-json to python将数据从 jquery-json 检索到 python
【发布时间】:2016-03-27 15:29:28
【问题描述】:

我正在使用 Python 开发一个应用引擎项目,将数据从 html 页面(使用 jQuery)发送到 Python。

我正在使用这个 jQuery 插件将 HTML 表序列化为 javascript 对象:https://github.com/lightswitch05/table-to-json

function addFood() {
    var table = $('#planTable').tableToJSON();
    var info = {
        "user": "{{user}}",
        "plan": JSON.stringify(table)
    };
    $.ajax({
        type: "POST",
        url: "/addplan",
        dataType: "json",
        data: JSON.stringify(info)
    })
    .done(function(msg) {
        alert(msg.text);
     });
}

在 Python 中我有那个代码:

class AddPlanToDB(webapp2.RequestHandler):
    def post(self):
        info = json.loads(self.request.body) #retrive data from jQuery
        print info
        user = info['user']
        template_values = {
            'text': 'All done!'
        }
        self.response.out.write(json.dumps(template_values))

打印 info 给我输出:

{u'plan': u'[{"Food":"Cheese, fontina","Grams":"100g","Pro":"25.6","Carbo":"1.6","Fat":"31.1","":""},{"Food":"Butter, salted","Grams":"50g","Pro":"0.4","Carbo":"0.0","Fat":"40.6","":""},{"Food":"Corn bran, crude","Grams":"200g","Pro":"16.7","Carbo":"171.3","Fat":"1.8","":""},{"Food":"","Grams":"Total:","Pro":"42.7","Carbo":"172.9","Fat":"73.5"}]', u'user': u'test@example.com'}

info['user'] 返回有关用户的正确信息。 但我无法检索有关

的数据

食物:

克:

专业版:

碳水化合物:

脂肪:

谁能告诉我如何在 Python 中获取这些数据?

提前谢谢我的小英语。

【问题讨论】:

    标签: javascript jquery python json google-app-engine


    【解决方案1】:

    要获取有关饮食计划的信息,请执行以下操作

    for item in json.loads(info['plan']):
        print item['Food']
        print item['Grams']
        print item['Pro']
        #etc
    

    这是一个复制粘贴示例

    import json
    data = {u'plan': u'[{"Food":"Cheese, fontina","Grams":"100g","Pro":"25.6","Carbo":"1.6","Fat":"31.1","":""},{"Food":"Butter, salted","Grams":"50g","Pro":"0.4","Carbo":"0.0","Fat":"40.6","":""},{"Food":"Corn bran, crude","Grams":"200g","Pro":"16.7","Carbo":"171.3","Fat":"1.8","":""},{"Food":"","Grams":"Total:","Pro":"42.7","Carbo":"172.9","Fat":"73.5"}]', u'user': u'test@example.com'}
    for item in json.loads(data['plan']):
        print item['Food']
    

    【讨论】:

    • 不工作:文件“main.py”,在后期打印项目['Food']中。 TypeError: 字符串索引必须是整数
    • @AndreaM,我在最初的例子中犯了一个错误。试试json.loads
    • 是的!最后!你有这个!我们需要调用 json.loads 2 次,我太笨了。真的谢谢@John!!
    • 替代调用json.loads 两次,只需在最初发送数据时仅调用一次JSON.stringify。你也不笨,你只是需要更多的练习=)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-06
    相关资源
    最近更新 更多