Postgres jsonb nested array append

人盡茶涼 提交于 2019-12-11 17:53:48

问题


I have simple table with a jsonb column

CREATE TABLE things (
  id SERIAL PRIMARY KEY,
  data jsonb
);

with data that looks like:

{
    "id": 1,
        "title": "thing",
        "things": [
            {
                "title": "thing 1",
                "moreThings": [
                    { "title": "more thing 1" }
                ]
            }
        ]
}

So how do I append inside of a deeply nested array like moreThings?

For single level nested array I could do this and it works:

UPDATE posts SET data = jsonb_set(data, '{things}', data->'things' || '{ "text": "thing" }', true);

But the same doesn't work for deeply nested arrays:

UPDATE posts SET data = jsonb_set(data, '{things}', data->'things'->'moreThings' || '{ "text": "thing" }', true)

How can I append to moreThings?


回答1:


It works just fine:

UPDATE things
SET data =
    jsonb_set(data,
              '{things,0,moreThings}',
              data->'things'->0->'moreThings' || '{ "text": "thing" }',
              TRUE
    )
WHERE id = 1;

If you have a table that consists only of a primary key and a jsonb attribute and you regularly want to manipulate this jsonb in the database, you are certainly doing something wrong. Your life will be much easier if you normalize the data some more.



来源:https://stackoverflow.com/questions/55060091/postgres-jsonb-nested-array-append

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