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

从 JSON 数组中获取 json 元素

如何解决从 JSON 数组中获取 json 元素

我有用于演示的示例数据,如下所示:

表格:

create table tbl_jdata
(
id int,jdata json
);

insert into tbl_jdata values(1,'[{"salary":10000,"name":"mak"},{"salary":20000,"name":"jak"},{"salary":45000,"name":"abc"}]');

我只想显示一个具有最高薪水的 json 元素,例如在预期结果中如下所示。

预期结果

id    jdata
-------------------------------------
1     [{"salary":45000,"name":"abc"}]

我的尝试

select t.id,each_section
from tbl_jdata t
cross join unnest(t.jdata) each_section
where t.id = 1 and (each_section ->> 'salary') in 
(
 select max(each_section ->> 'salary')
 from tbl_jdata t
 cross join unnest(t.jdata) each_section
);

出现错误

ERROR: function unnest(json) does not exist

解决方法

您需要在 JSON 数组上使用 int size = 0; for (int i = 0; i < texts.length; i++) { if (texts[i] != null) { for (int j = 0; j < texts[i].length; j++) { // If the 1st letter matches if (texts[i][j] == searchText[0]) { // then iterate over the size of the "searchtext" for (int k = 1; k < searchText.length; k++) { // If the position of the next letter exists & is equal to // what is in the search word,then increment some variable if ((i + k < texts.length && texts[i + k] != null && j + k < texts[i + k].length) && texts[i + k][j + k] == searchText[k]) { size += 1; } // If we are on the last letter if (k == searchText.length - 1) { // return true if we have found the search word if (size == searchText.length - 1) { return true; } else { // Otherwise reset the size and // keep iterating over the texts[][] size = 0; } } } } } } } return false; 评估器而不是 CREATE PROCEDURE SP_INS_PUBLIC_NHANVIEN @MANV VARCHAR(20),@HOTEN NVARCHAR(100),@EMAIL VARCHAR (20),@LUONGCB VARCHAR(100),@TENDN NVARCHAR(100),@MK VARCHAR(100) AS BEGIN SET NOCOUNT ON; DECLARE @SQL NVARCHAR(MAX); IF ASYMKEY_ID(@MANV) IS NULL BEGIN SET @SQL = 'CREATE ASYMMETRIC KEY ' + QUOTENAME(@MANV) + ' ' + 'WITH ALGORITHM = RSA_2048 ' + 'ENCRYPTION BY PASSWORD = ' + QUOTENAME(@MK,NCHAR(39)) EXEC (@SQL) END DECLARE @MATKHAU_SHA1 VARBINARY(MAX); SET @MATKHAU_SHA1 = CONVERT(VARBINARY(MAX),HASHBYTES('SHA1',@MK)); DECLARE @LUONG_RSA512 VARBINARY(MAX); SET @LUONG_RSA512 = ENCRYPTBYASYMKEY(ASYMKEY_ID(@MANV),@LUONGCB); DECLARE @PUBKEY NVARCHAR(20); SELECT @PUBKEY = CONVERT(NVARCHAR(20),@MANV); INSERT INTO DBO.NHANVIEN VALUES (@MANV,@HOTEN,@EMAIL,ENCRYPTBYASYMKEY(ASYMKEY_ID(@MANV),@LUONGCB),@TENDN,@MATKHAU_SHA1,@PUBKEY); END GO 。这样做之后,您可以使用横向连接来获取最高元素:

json_array_elements()

请注意,建议使用 unnest() 而不是 select t.id,i.* from the_table t cross join lateral ( select x.item from json_array_elements(t.jdata) as x(item) order by (x.item ->> 'salary')::int desc limit 1 ) i

,

你需要使用jsonb,这里我给你发个参考。

https://www.compose.com/articles/faster-operations-with-the-jsonb-data-type-in-postgresql/

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