python解析json数组转sql_在Python中将数组数组转换为JSON

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... ]

解决方案

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值