Postgresql : Append element in json array objects

烂漫一生 提交于 2021-02-11 13:24:34

问题


I have below jsonb data stored in table column as below:

'{"info":[
    {
        "database": "Oracle",
        "company" : "Oracle"
    },
    {
        "database":"Sql Server",
        "company" :"Microsoft"
    },
    {
        "database":"DB2",
        "company" :"IBM"
    }
]}'

i need to append a element "License" : "Proprietary" to all objects present in json array like below:

'{"info":[
    {
        "database": "Oracle",
        "company" : "Oracle",
        "License" : "Proprietary"
    },
    {
        "database":"Sql Server",
        "company" :"Microsoft",
        "License" : "Proprietary"
    },
    {
        "database":"DB2",
        "company" :"IBM",
        "License" : "Proprietary"
    }
]}'

i have added the sql fiddle link here: https://dbfiddle.uk/?rdbms=postgres_11&fiddle=3990e79140df1c897aac2fb19364d2e9

Thanks in advance.


回答1:


You need to call set_jsonb on each array element individually, getting the values with jsonb_array_elements and aggregating them back into a json array with jsonb_agg:

UPDATE test
SET data = jsonb_set(data, '{info}', (
  SELECT jsonb_agg(el || '{"License" : "Proprietary"}')
  FROM jsonb_array_elements(data -> 'info') el
));

(Updated dbfiddle demo)



来源:https://stackoverflow.com/questions/63758141/postgresql-append-element-in-json-array-objects

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!