简体   繁体   English

Postgres:如何更改数组中每个元素的 jsonb 值类型?

[英]Postgres: How to alter jsonb value type for each element in an array?

I have a jsonb column named items in Postgres 10.12 like this:我在 Postgres 10.12 中有一个名为items的 jsonb 列,如下所示:

{
    "items": [
        {
            "itemQty": 2,
            "itemName": "snake"
        },
        {
            "itemQty": 1,
            "itemName": "x kodiyum"
        }
    ]
}

Now I want to convert itemQty type to string for every array element so that the new values are like this:现在我想将每个数组元素的itemQty类型转换为字符串,以便新值如下所示:

{
    "items": [
        {
            "itemQty": "2",
            "itemName": "snake"
        },
        {
            "itemQty": "1",
            "itemName": "x kodiyum"
        }
    ]
}

How do I do this?我该怎么做呢? I have gone through the documentation for Postgres jsonb and couldn't figure out.我已经浏览了 Postgres jsonb 的文档,但无法弄清楚。

On the server-side, I am using Spring boot and Hibernate with com.vladmihalcea.hibernate.type.json (Hibernate Types 52) if it helps. On the server-side, I am using Spring boot and Hibernate with com.vladmihalcea.hibernate.type.json (Hibernate Types 52) if it helps.

Thanks谢谢

You could unnest the array, modify the elements, and then rebuild it.您可以取消嵌套数组,修改元素,然后重新构建它。 Assuming that the primary key of your table is id , that would be:假设您的表的主键是id ,那就是:

select jsonb_build_object(
    'items', jsonb_agg(
        jsonb_build_object(
            'itemQty',  (x.obj ->> 'itemQty')::text,
            'itemName', x.obj ->> 'Name'
        )
    ) 
    )new_items
from mytable t
cross join lateral jsonb_array_elements(t.items -> 'items') as x(obj)
group by id

Note that the explicit cast to ::text is not really needed here, as ->> extract text values anyway: I kept it because it makes the intent clearer.请注意,这里并不真正需要显式转换为::text ,因为->>无论如何都提取文本值:我保留它是因为它使意图更清晰。

If you want an update statement:如果您想要update声明:

update mytable t
set items = (
    select jsonb_build_object(
        'items', jsonb_agg(
            jsonb_build_object(
                'itemQty',  (x.obj ->> 'itemQty')::text,
                'itemName', x.obj ->> 'Name'
            )
        ) 
    )
    from jsonb_array_elements(t.items -> 'items') as x(obj)
)

Demo on DB Fiddle DB Fiddle 上的演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM