微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在PostgreSQL命令行psql里格式化输出json字段

在pgsql的psql命令里直接select输出json字段是一长串字符,这对阅读非常不友好,查了好久也没查到pgsql有格式化输出json字段的函数,只好折腾一番。

表结构如下:

pgsql=#\dtest
资料表"pgsql.test"
栏位|型别|修饰词
------+---------+--------
id|integer|非空
info|jsonb|非空
索引:
"test_pkey"PRIMARYKEY,btree(id)
"test_info_idx"gin(info)

SELECT的格式化输出

pgsql=#selectid,replace(
replace(
regexp_replace(info::text,',"',concat(',chr(10),chr(9),'"'),'g'),'{',concat('{',chr(9))),'}',concat(chr(10),'}'))asinfofromtest;
id|info
----+---------------------------------------------------------------
1|{+
|"a":[1,2,3],+
|"b":[4,5,6]+
|}
2|{+
|"a":[7,8,9],+
|"b":[10,11,12]+
|}
3|{+
|"guid":"9c36adc1-7fb5-4d5b-83b4-90356a46061a",+
|"name":"AngelaBarton",+
|"tags":["enim",+
|"aliquip",+
|"qui"],+
|"address":"178Howardplace,Gulf,Washington,702",+
|"company":"Magnafone",+
|"latitude":19.793713,+
|"is_active":true,+
|"longitude":86.513373,+
|"registered":"2009-11-07T08:53:22+08:00"+
|}
(3行记录

为了方便今后每次调用,写成函数

createfunctionformat_json(text)returnstextas$$
selectreplace(replace(regexp_replace($1,'}'))asjson_s;
$$languagesql;

这样看起来就简洁直观多了:

pgsql=#selectid,format_json(info::text)asinfofromtestwhereid=3;
id|info
----+---------------------------------------------------------------
3|{+
|"guid":"9c36adc1-7fb5-4d5b-83b4-90356a46061a",+
|"registered":"2009-11-07T08:53:22+08:00"+
|}
(1行记录)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐