0

I'm fetching data from Mysql from table person(id, name, email). The table has many rows. I'm trying to put into a json array in a loop. But in the json array it gets overwritten with the new array.

   for row in results:
        persons = {
                     [{
                        'personId' : row[0],
                        'personName' : row[1],
                        'personEmail' : row[2]
                    },]
                 }
    print json.dumps(persons)

can anybody give a solution?

1 Answer 1

1

In your code, in each iteration of the for loop, you're rebuilding persons as a Python dictionary with one member which is the current row, not adding more rows ("people") to the dictionary. You need to rewrite that, something along the lines of :

persons={}
for row in results:
    persons[row[0]] = {                    
                        'personId' : row[0],
                        'personName' : row[1],
                        'personEmail' : row[2]                    
                 }
print json.dumps(persons)
Sign up to request clarification or add additional context in comments.

3 Comments

hey, for this solution, i get the result in this format code { "1": { "personId": 1, "personName": "Amritha D", "personEmail": "[email protected]" }, "2": { "personId": 2, "personName": "Aishwarya R", "personEmail": "[email protected]" } } but i want the json array without the indexes "1","2", in this format code { { "personId": 1, "personName": "Amritha D", "personEmail": "[email protected]" }, { "personId": 2, "personName": "Aishwarya R", "personEmail": "[email protected]" } }
So don't use a dictionary, but a list. initialize persons=[] and just use persons.append(....) in each iterator of the for loop.
It works well when i'm using json.dumps(persons) but I also want to send it as a response in my web application. So, when i use jsonify(persons) (using flask) it gives an error. I dont know why?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.