如何使用MySQLDB从MySQL创建一个JSON数个结构阵列,并控制JSON风格化字段名称?
我有一个半复合Python / MySQLDB问题,可以选择数据库中的数据并将其转换为特定的JSON结构。
工作后,我将使用更新的工作解决方案编辑此帖子。
首先数据库
- 表:'人'
- id
- first_name
- last_name
每行代表一个人。对于JSON输出,我需要一个结构数组。每个 数组的元素是代表表中一行的结构。
要求:
- 我正在将python与mysqldb一起选择数据,因此需要一个有效的解决方案 使用mysqldb,
- 启动和最终字符必须是'{''and}',而不是'['and']'
- JSON风格化字段的命名与DB表字段名称的命名不同,所以我 需要控制
- DB表名的名称,可能与我想要或需要的JSON名称所需的内容不同 阵列,所以我需要控制
我要创建一个看起来像这样的结构,每个结构 行将是数组中的一个元素:
{
"persons": [
{
"personId": 1,
"firstName": "<first_name>",
"lastName": "<last_name>"
},
{
"personId": 2,
"firstName": "<first_name>",
"lastName": "<last_name>"
}
]
}
I have a semi-complex Python / MySQLdb problem with selecting data from a database and converting that to a specific JSON structure.
I will edit this post with an updated working solution, once working.
First the database table
- table:'person'
- id
- first_name
- last_name
Each row represents a person. For the json output, I need an array of structs. Each
element of the array is a struct that represents a row in the table.
Requirements:
- I am using Python with MySQLdb to select the data, and so need a solution that works
with MySQLdb - The starting and end character would have to be '{' and '}', and not '[' and ']'
- The json stylized fields may be named differently from the DB table field names, so I
need to have control of that - The DB table name, may be different than what I want or need for the name of the json
array, so I need control of that
I want to create an array of structs that would look something like this, where each
row would be an element in the array:
{
"persons": [
{
"personId": 1,
"firstName": "<first_name>",
"lastName": "<last_name>"
},
{
"personId": 2,
"firstName": "<first_name>",
"lastName": "<last_name>"
}
]
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以以这种方式在SQL中执行此操作(假设MySQL 5.7.22或更高版本),
或者,您可以进行简单的查询,获取结果并在Python中构建一个DICT对象数组,然后使用
json.dumps()。
You can do this in SQL this way (assuming MySQL 5.7.22 or later)
Alternatively, you could do a simple query, fetch the results, and build an array of dict objects in Python, then convert the whole array to JSON using
json.dumps()
.