postgresql - 将 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 有很多内置的 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
推荐阅读
- ios - UIApplicationMain 和 UIApplication 有什么区别
- python-3.x - 如何在 for 循环中使用 groupby 组
- swift - 如何从应用程序中删除用户默认值?
- r - 循环 dplyr 并创建多个数据框
- c++ - 在c ++中将csv读取的十六进制字符串值转换为uint8_t
- android - 录制视频时查询支持的比特率
- php - nginx 通用重写规则
- java - 如何在搜索视图中拥有多个按钮?
- google-cloud-platform - cloudrun(或 knative)上的简单 HelloWorld 应用程序似乎太慢了
- ruby - 如何优化代码 - 它有效,但我知道我缺少很多学习