在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行记录)原文链接:https://www.f2er.com/postgresql/194811.html