如何使用MySQLDB从MySQL创建一个JSON数个结构阵列,并控制JSON风格化字段名称?

发布于 2025-01-22 10:20:56 字数 830 浏览 2 评论 0原文

我有一个半复合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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

你的呼吸 2025-01-29 10:20:56

您可以以这种方式在SQL中执行此操作(假设MySQL 5.7.22或更高版本),

SELECT JSON_OBJECT(
    'persons',
    JSON_ARRAYAGG(
      JSON_OBJECT(
        'personId', id,
        'firstName', first_name,
        'lastName', last_name
      )
    )
  ) AS `result`
FROM mytable;

或者,您可以进行简单的查询,获取结果并在Python中构建一个DICT对象数组,然后使用json.dumps()。

You can do this in SQL this way (assuming MySQL 5.7.22 or later)

SELECT JSON_OBJECT(
    'persons',
    JSON_ARRAYAGG(
      JSON_OBJECT(
        'personId', id,
        'firstName', first_name,
        'lastName', last_name
      )
    )
  ) AS `result`
FROM mytable;

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文