如何解决格式化 JSON 数组数据
包含样本数据的表格:
create table tbl_jsdata
(
id int,p_id int,field_name text,field_value text
);
insert into tbl_jsdata values
(1,101,'Name','Sam'),(2,'City','dubai'),(3,'Pin','1235'),(4,'Country','UAE'),(5,102,(6,(7,'Sam Jack');
json_agg 查询:
select p_id,json_agg(distinct jsonb_build_object(field_name,field_value)) jsdata
from tbl_jsdata
group by p_id;
得到结果:
p_id jsdata
--------------------------------------------------------------------------------
101 [{"City": "dubai"},{"Country": "UAE"},{"Name": "Sam"},{"Pin": "1235"}]
102 [{"City": "dubai"},{"Name": "Sam Jack"}]
预期结果:
p_id jsdata
--------------------------------------------------------------------------------
101 [{"City": "dubai","Country": "UAE","Name": "Sam","Pin": "1235"}]
102 [{"City": "dubai","Name": "Sam"},{"Name": "Sam Jack"}]
解决方法
也许您想使用 json_object_agg
函数:
postgres=# select p_id,json_object_agg(field_name,field_value) from tbl_jsdata group by p_id;
┌──────┬─────────────────────────────────────────────────────────────────────────┐
│ p_id │ json_object_agg │
╞══════╪═════════════════════════════════════════════════════════════════════════╡
│ 101 │ { "Name" : "Sam","City" : "Dubai","Pin" : "1235","Country" : "UAE" } │
│ 102 │ { "Name" : "Sam","Name" : "Sam Jack" } │
└──────┴─────────────────────────────────────────────────────────────────────────┘
(2 rows)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。