本文介绍了在Python中将数组数组转换为JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组数组,该数组是使用 SQLAlchemy 从数据库查询中获得的,我想做两件事。

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


  • 我想获取列的名称(或类似从表中选择 SELECT fullname AS name n'surname 之类的东西)。

  • I想要将最终产品转换为对象的json数组,以便可以在前端使用它。

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

这是 print的输出(结果)

如果我使用 json .dump(results)我明白了:

现在更具体地说,我正在尝试最终是这样的:

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


推荐答案

您只需在元组列表中循环以创建字典,然后可以将其转换为JSON。像这样的东西:

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)

这篇关于在Python中将数组数组转换为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 01:54