PostgreSQL - Add key to each objects of an JSONB array

▼魔方 西西 提交于 2020-01-24 19:22:39

问题


My database contains a table which has a column with jsonb type, and I want to update a part of these data using functions/operators from postgreSQL. Given we have this:

{
  "A":[
    {"index":"1"},
    {"index":"2"}
  ],
  "B":[
    {"index":"3"},
    {"index":"4"}
  ]
}

Let's say we went to add a key with an empty array to objects from "A" array, in order to have:

{
  "A":[
    {"index":"1", "myArray":[]},
    {"index":"2", "myArray":[]}
  ],
  "B":[
    {"index":"3"},
    {"index":"4"}
  ]
}

How can I proceed?

I've already tried this kind of things without success:

UPDATE myTable SET myColumn = (myColumn::jsonb)->>'A' || '{"myArray":[]}'

UPDATE myTable SET myColumn = (
  SELECT jsonb_agg(jsonb_set(
    element, 
    array['A'], 
    to_jsonb(((element ->> 'A')::jsonb || '{"myArray":[]}')::jsonb)
  ))
  FROM jsonb_array_elements(myColumn::jsonb) element
)::json

UPDATE myTable SET myColumn = (
  SELECT jsonb_each((element ->> 'A')::jsonb) || '{"myArray":[]}'::jsonb
  FROM jsonb_array_elements(myColumn::jsonb) element
)::json

Obviously, all of these tests have been big failure. I have difficulties to understand how works postgreSQL functions.

Somebody can help?


回答1:


The approach with jsonb_array_elements and jsonb_set was the right idea, but somehow you nested them the wrong way round:

UPDATE myTable SET myColumn = jsonb_set(myColumn, '{A}', (
  SELECT jsonb_agg( element || '{"myArray":[]}' )
  FROM jsonb_array_elements(myColumn -> 'A') element
));

(online demo)

Btw if your column already has jsonb data type, you shouldn't need any casts.



来源:https://stackoverflow.com/questions/58959678/postgresql-add-key-to-each-objects-of-an-jsonb-array

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