0

I am working on an app engine project in Python, sending data from an html page (using jQuery) to Python.

I am using this jQuery plugin to serialize HTML tables into javascript objects: 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);
     });
}

In Python i have that code:

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))

Print info give me that output:

{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'[email protected]'}

Table structure that give me data

info['user'] return the correct information about user. But i can't retrieve data about

Food:

Grams:

Pro:

Carbo:

Fat:

Can anyone tell me how to get this data in Python?

Thanks in advance and sorry for my little english.

1 Answer 1

1

To get the information about the diet plan do something like this

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

Here's a copy and paste example

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'[email protected]'}
for item in json.loads(data['plan']):
    print item['Food']
Sign up to request clarification or add additional context in comments.

4 Comments

Not working: File "main.py", in post print item['Food']. TypeError: string indices must be integers
@AndreaM, I made a mistake in the initial example. Try it with the json.loads
Yes! Finally! You got this! We need to call json.loads 2 times, i'm so dumb. Really thank you @John!!
Alternately instead of calling json.loads twice, simply call JSON.stringify only once when you initially send the data. Also you're not dumb, you just need more practice =).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.