Postgres用于将具有重叠键的两个json对象合并为一个对象

时间:2015-10-25 18:10:02

标签: sql json postgresql postgresql-9.3

我有以下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'

2 个答案:

答案 0 :(得分:4)

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)

答案 1 :(得分:3)

答案涉及 Postgres 9.4和9.3。

示例数据:

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 0 priority, jsonb_each(val->'b') elem
from test_js
union all
select 1 priority, jsonb_each(val->'a') elem
from test_js
order by 1

 priority |  elem  
----------+--------
        0 | (1,10)
        0 | (2,8)
        0 | (4,12)
        1 | (0,2)
        1 | (1,4)
        1 | (3,6)
(6 rows)

接下来,从结果集中选择具有唯一键的元素:

select distinct on ((elem).key) elem
from (
    select 0 priority, jsonb_each(val->'b') elem
    from test_js
    union all
    select 1 priority, jsonb_each(val->'a') elem
    from test_js
    ) sub

  elem  
--------
 (0,2)
 (1,10)
 (2,8)
 (3,6)
 (4,12)
(5 rows)    

最后,将结果聚合到json对象中:

select json_object_agg((elem).key, (elem).value) result
from (
    select distinct on ((elem).key) elem
    from (
        select 0, jsonb_each(val->'b') elem
        from test_js
        union all
        select 1, jsonb_each(val->'a') elem
        from test_js
        ) sub
    ) sub

                      result                       
---------------------------------------------------
 { "0" : 2, "1" : 10, "2" : 8, "3" : 6, "4" : 12 }
(1 row)

Postgres 9.3 中,您可以使用json_object_agg模拟string_agg

select format('{ %s }', 
    string_agg(format('"%s" : %s', (elem).key, (elem).value), ', '))::json result
from (
    select distinct on ((elem).key) elem
    from (
        select 0, json_each(val->'b') elem
        from test_js
        union all
        select 1, json_each(val->'a') elem
        from test_js
        ) sub
    ) sub

                      result                       
---------------------------------------------------
 { "0" : 2, "1" : 10, "2" : 8, "3" : 6, "4" : 12 }
(1 row)     

顺便说一下,你的json值无效,应该是

{
    "a": {
        "0": 2,
        "1": 4,
        "3": 6
    },
    "b": {
        "1": 10,
        "2": 8,
        "4": 12
    }
}

请使用JSONLint验证json值。