-1

I have an array of arrays which I get from a database query using SQLAlchemy and I want to do two things.

  • I want to get the name of the columns (or something like SELECT fullname AS "name n' surname" from table).
  • I want to convert the final product to a json array of objects, so that I can use it on the front-end.

I have searched several hours and couldn't find an answer that works for my case.

Here is the line of code querying the database and storing it in results variable:

results = session.query(categories.categoryname, products.pack, products.price, products.checkstate).join(products).all()

Here is the output of print(results):

[('chocolate', '3', 5, False), ('chocolate', '5', 7, False), ('chocolate', '10', 10, False), ('honey', '3', 5, False), ('honey', '5', 7, False), ('honey', '10', 10, False), ('candy', '3', 5, False), ('candy', '5', 7, False), ('candy', '10', 10, False)]

If I use json.dump(results) I get this:

[["chocolate", "3", 5, false], ["chocolate", "5", 7, false], ["chocolate", "10", 10, false], ["honey", "3", 5, false], ["honey", "5", 7, false], ["honey", "10", 10, false], ["candy", "3", 5, false], ["candy", "5", 7, false], ["candy", "10", 10, false]]

Now to be more specific, what I'm trying to end up with is this:

[{"type": "chocolate", "pack": "3", "price": 5, "checkstate": false}, ....etc... ]

0

1 Answer 1

1

You can simply loop through your list of tuples to create dictionaries, which then can be converted to a JSON. Something like this:

import json

data = [('chocolate', '3', 5, False), ('chocolate', '5', 7, False), ('chocolate', '10', 10, False), ('honey', '3', 5, False), ('honey', '5', 7, False), ('honey', '10', 10, False), ('candy', '3', 5, False), ('candy', '5', 7, False), ('candy', '10', 10, False)]

list = [{"pack": x[0], "pack": x[1], "price": x[2], "checkstate": x[3]} for x in data]

json.dumps(list)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.