poStrgesQL:从JSONB值的嵌套数组字段编辑特定字段
表:
table Bar(
id int,
my_json jsonb
)
my_json
的示例:
{
"foo": "bar",
"columns": [
{
"type": "integer",
"field": "myField",
"children": [
{
"type": "integer",
"field": "myField"
}
]
},
{
"type": "integer",
"field": "otherField",
"children": [
{
"type": "integer",
"field": "myField"
}
]
},
{
"type": "integer",
"field": "baz",
"children": null
}
]
}
我需要更改所有“ type”:“ integer”
“ type” type“:“ string” 匹配<代码>“字段”
等于“ myfield”
。
我使用此下一个SQL查询制作了LVL 1(在列
lvl):
with query as (
select ('{columns,' || index - 1 || ',type}')::text[] as path,
b.id
from Bar b,
jsonb_array_elements(my_json -> 'columns') with ordinality arr(col, index)
where col ->> 'field' = 'myField'
and col ->> 'type' = 'integer'
)
update Bar b
set my_json = jsonb_set(b.my_json, query.path, '"string"', false)
from query
where b.id = query.id;
我必须使用Nested Array 可以实现LVL 2(理想地了解任何LVL)保持无效,我不知道该怎么做。
The table:
table Bar(
id int,
my_json jsonb
)
Example of what my_json
looks like:
{
"foo": "bar",
"columns": [
{
"type": "integer",
"field": "myField",
"children": [
{
"type": "integer",
"field": "myField"
}
]
},
{
"type": "integer",
"field": "otherField",
"children": [
{
"type": "integer",
"field": "myField"
}
]
},
{
"type": "integer",
"field": "baz",
"children": null
}
]
}
I need to change all the "type": "integer"
to "type": "string"
where the matching "field"
equals to "myField"
.
I made the lvl 1 (at columns
lvl) with this next sql query:
with query as (
select ('{columns,' || index - 1 || ',type}')::text[] as path,
b.id
from Bar b,
jsonb_array_elements(my_json -> 'columns') with ordinality arr(col, index)
where col ->> 'field' = 'myField'
and col ->> 'type' = 'integer'
)
update Bar b
set my_json = jsonb_set(b.my_json, query.path, '"string"', false)
from query
where b.id = query.id;
I have to achieve the lvl 2 (ideally understand any lvl) with the nested array children
which may be null, and I don't know how to do it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我做到了!这是我发现的解决方案:
说明:
列
索引及其bar ID - &gt;non_null_children < / code>
我不知道这是否是最优化的解决方案,如果您认为这是必要的。
I made it! Here's the solution I found:
Explanation:
columns
index and its Bar id ->non_null_children
I don't know if this is the most optimized solution, feel free to improve it if you think it's necessary.