首页 > 解决方案 > 将 Json 文本更改为 json 数组

问题描述

目前在我的表数据是这样的

字段名称:作者

字段数据:json形式

当我们运行选择查询 SELECT bs.author FROM books bs;时,它会返回这样的数据

"[{\"author_id\": 1, \"author_name\": \"It happend once again\", \"author_slug\": \"fiction-books\"}]"

但我需要选择的数据应该是这样的

    [
        {
          "author_id": 1,
          "author_name": "It happend once again",
          "author_slug": "fiction-books"
        }
    ]

数据库:PostgreSql

注意:请避免 PHP 代码或 PHP 代码的迭代

标签: postgresql

解决方案


答案取决于您使用的 PostgreSQL 版本以及您使用的客户端,但 PostgreSQL 有很多内置的 json 处理功能。

https://www.postgresql.org/docs/10/functions-json.html

你的目标也没有明确定义......如果你想做的只是漂亮地打印 json,这包括在内。

# select jsonb_pretty('[{"author_id": 1,"author_name":"It happend once again","author_slug":"fiction-books"}]') as json;
                      json
-------------------------------------------------
 [                                              +
     {                                          +
         "author_id": 1,                        +
         "author_name": "It happend once again",+
         "author_slug": "fiction-books"         +
     }                                          +
 ]

相反,如果您正在寻找如何从 json 填充 postgres 记录集,则还包括:

# select * from json_to_recordset('[{"author_id": 1,"author_name":"It happend once again","author_slug":"fiction-books"}]')
as x(author_id text, author_name text, author_slug text);

 author_id |      author_name      |  author_slug
-----------+-----------------------+---------------
 1         | It happend once again | fiction-books

推荐阅读