[英]How to get a specific value in a json object array and save into a var
[英]How to update a specific value of a object present in array of object within Postgres JSON Field
这是我的 JSON 字段值。 它存储在 PostgreSQL 表中。 我想搜索和更新的特定user_name
在user
关键
{
"user": [
{
"user_name": "Devang",
"user_weight": 0.7676846955248864
},
{
"user_name": "Meet",
"user_weight": 0.07447325861051013
},
{
"user_name": "L.b.vasoya",
"user_weight": 0.056163873153859706
}
],
"address": [
{
"address_name": "India"
}
]
}
例如,他的名字是Devang
to Dev
使用 Django JSONField
"user": [
{
"user_name": "Dev",
"user_weight": 0.7676846955248864
},
....
我已经尝试了RAWQuery来查找。 这是查询。
select json_field->user from user_table where json_field @> '{"user": [{"user_name": "Devang"}]}';
它会像这样返回
{
"user_name": "Devang",
"user_weight": 0.7676846955248864
},
{
"user_name": "Meet",
"user_weight": 0.07447325861051013
},
{
"user_name": "L.b.vasoya",
"user_weight": 0.056163873153859706
}
]
我也试过JSON_SET来更新 user_name 但JSON_SET只接受。 它将更新上层,而不是嵌套层
在嵌套元素更新的情况下,使用JSONB_SET
有点棘手。 如果要先设置嵌套元素的值,则需要获取要更新的元素的确切路径。 请尝试以下查询:
with cte as (
select id, ('{user,'||index-1||',user_name}')::text[] as json_path
from user_table, jsonb_array_elements(json_field->'user')
with ordinality arr(vals,index) where arr.vals->>'user_name' ='Devang' --put the value to be replaced
)
update user_table
set json_field = jsonb_set(json_field,cte.json_path,'"Dev"',false) --put the new value in '""' here
from cte where user_table.id=cte.id;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.