json - 如何在 FLASK 中创建分层 json 响应
解决方案
由于您已使用flask标记您的问题,因此本文假设您也在使用 Python。要将数据库值格式化为 JSON 字符串,您可以查询 db,然后使用递归:
import sqlite3, collections
d = list(sqlite3.connect('file.db').cursor().execute("select * from values"))
def get_tree(vals):
_d = collections.defaultdict(list)
for a, *b in vals:
_d[a].append(b)
return [{'name':a, **({} if not (c:=list(filter(None, b))) else {'children':get_tree(b)})} for a, b in _d.items()]
import json
print(json.dumps(get_tree(d), indent=4))
输出:
[
{
"name": "AA",
"children": [
{
"name": "BB",
"children": [
{
"name": "EE",
"children": [
{
"name": "JJ",
"children": [
{
"name": "EEV"
},
{
"name": "FFW"
}
]
},
{
"name": "KK",
"children": [
{
"name": "HHX"
}
]
}
]
}
]
},
{
"name": "CC",
"children": [
{
"name": "FF",
"children": [
{
"name": "LL",
"children": [
{
"name": "QQY"
}
]
},
{
"name": "MM",
"children": [
{
"name": "RRV"
}
]
}
]
},
{
"name": "GG",
"children": [
{
"name": "NN",
"children": [
{
"name": "SSW"
}
]
}
]
}
]
},
{
"name": "DD",
"children": [
{
"name": "HH",
"children": [
{
"name": "OO",
"children": [
{
"name": "TTZ"
}
]
}
]
},
{
"name": "II",
"children": [
{
"name": "PP",
"children": [
{
"name": "UUW"
}
]
}
]
}
]
}
]
}
]
推荐阅读
- python - 尝试使用 smtplib 和 email.mime.multipart 从 python 发送电子邮件,收到错误“'Series' object has no attribute 'encode'”
- python - 从字典中打印值而不重复?
- android - PorterDuff.Mode.CLEAR 在画布上绘制黑色
- javascript - 反应原生 upi 付款被拒绝
- flutter - 如何仅在 Sqlite(或 Flutter 中的 sqflite)中获取今天的记录?
- javascript - 无法读取未定义的属性“排序”
- reactjs - 在 reactjs 中本地运行 webpack
- android - 使用获取导航时,颤振处置功能在我的视频控制器上不起作用
- git - CircleCi 使用 CIRCLE_COMPARE_URL 中断工作
- xero-api - Xero Payroll AU Payruns API - 检索 Payruns 时未定义工资单