我有以下 json 对象:
{
"a" : {
"0" : 2,
"1" : 4,
"3" : 6,
}
"b" : {
"2" : 8,
"1" : 10, /*note this key exists in "a" too*/
"4" : 12,
}
}
我想生成以下对象,然后能够像这样从中提取元素:
{
"0" : 2,
"1" : 10,
"2" : 8,
"3" : 6,
"4" : 12,
}
提取:object->>'1'
应该返回 '10'
基本上我有两个数组,它们可能有重叠的键,我想合并这两个数组,让一个数组优先。
我怎样才能做到这一点?理想情况下,我会调用类似 arrayMerge(a, b)
的函数它给了'a'
优先级高于 'b'
最佳答案
在 Postgres 9.5+ 中,您可以简单地使用内置的连接运算符 ||
来合并 JSON 对象。
create table test_js(val jsonb);
insert into test_js values ('{"a":{"0":2,"1":4,"3":6},"b":{"1":10,"2":8,"4":12}}');
select (val->'a') || (val->'b') from test_js;
?column?
--------------------------------------------
{"0": 2, "1": 10, "2": 8, "3": 6, "4": 12}
(1 row)
关于sql - Postgres函数将两个具有重叠键的json对象合并为一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33333161/