Skip to content
Advertisement

while Convert sql query to json getting wrong output

# print(qry1.fetchall()) 
# print this [(1716, 'Mumbai Indians')]
# print(self.curs.description) 
# print this (('Highest_Extra_Runs', None, None, None, None, None, None), 
('Team', None, None, None, None, None, None))

items = []
for row in qry1:
    for
key in self.curs.description:
items.append({key[0]: value for value in row})
print(json.dumps({'items': items}))

I am getting wrong output

{"items": [{"Highest_Extra_Runs": "Mumbai Indians"}, {"Team": "Mumbai Indians"}]}

Output should be:

{"items": [{"Highest_Extra_Runs": 1716}, {"Team": "Mumbai Indians"}]}

Advertisement

Answer

The problem is with your nested loops. You actually want to parallely iterate both lists. The lists themselves are quite complex due to the nesting of lists and tuples. That’s why you may loose track here. You could try simplifying the lists/objects if possible or storing parts of them in extra variables. It will make your job easier when dealing with them.

Now the solution to your problem: Instead of looping in foreach-manner, use an index and access the particular values in both lists/tuples.

items = []
for i in range(len(qry1[0])):
    items.append({self.curs.description[i][0]: qry1[0][i]})
print(json.dumps({'items': items}))

# Output:
{"items": [{"Highest_Extra_Runs": 1716}, {"Team": "Mumbai Indians"}]}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement