问题
json Request:
INSERT INTO test.demotbl (data)
VALUES ('{
"x1": "Americas",
"x2": "West",
"x3": [{
"x_id": "sam"
}],
"x4": {
"a1": true,
"a2": false,
"a3": [
"xx",
"xx"
],
"a4": [
"Josh"
],
"y1": [{
"id": "RW",
"z2": true,
"z3": "USER",
"z4": [{
"name": "john"
}]
},
{
"id": "RO",
"z2": false,
"z3": "SELECT",
"z4": [{
"name": "salin"
}
{
"id": "DBA",
"z2": false,
"z3": "SELECT",
"z4": [{
"name": "Samule"
}]
}
]
}
}'::jsonb)
Question 1 :how can i delete the the array values where "id":"RO" from y1 array ? There can be any no of element in the y1 json array i want to delete the array value based on id condition.
how can i delete the the array values where "id":"RO" from y1 array ? There can be any no of element in the y1 json array i want to delete the array value based on id condition.
Expected Output after deleting:
{
"x1": "Americas",
"x2": "West",
"x3": [{
"x_id": "sam"
}],
"x4": {
"a1": true,
"a2": false,
"a3": [
"xx",
"xx"
],
"a4": [
"Josh"
],
"y1": [{
"id": "RW",
"z2": true,
"z3": "USER",
"z4": [{
"name": "john"
}]
},
{
"id": "DBA",
"z2": false,
"z3": "SELECT",
"z4": [{
"name": "Samule"
}]
}
]
}
}
Question 2 : How can i only delete the "id":"RO" from the y1 array
Expected Output:
{
"x1": "Americas",
"x2": "West",
"x3": [{
"x_id": "sam"
}],
"x4": {
"a1": true,
"a2": false,
"a3": [
"xx",
"xx"
],
"a4": [
"Josh"
],
"y1": [{
"id": "RW",
"z2": true,
"z3": "USER",
"z4": [{
"name": "john"
}]
},
{
"z2": false,
"z3": "SELECT",
"z4": [{
"name": "salin"
}
{
"id": "DBA",
"z2": false,
"z3": "SELECT",
"z4": [{
"name": "Samule"
}]
}
]
}
}
回答1:
Edit note: I misunderstood the question. Thought you wanted to delete the whole object containing 'RO'. I edited the answer so as just to delete the id.
There is a small error in the jsonb object you provide. It should probably look like this:
{
"x1": "Americas",
"x2": "West",
"x3": [{
"x_id": "sam"
}],
"x4": {
"a1": true,
"a2": false,
"a3": [
"xx",
"xx"
],
"a4": [
"Josh"
],
"y1": [{
"id": "RW",
"z2": true,
"z3": "USER",
"z4": [{
"name": "john"
}]
},
{
"id": "RO",
"z2": false,
"z3": "SELECT",
"z4": [{
"name": "salin"
}]
},
{
"id": "DBA",
"z2": false,
"z3": "SELECT",
"z4": [{
"name": "Samule"
}]
}
]
}
}
With that said, this should work, but keep in mind - this will replace all entries in the working table. The jsonb objects are in the field "field".
with zd as (select ('{x4,y1,'||index-1||',id}')::text[] as path
from table
,jsonb_array_elements((field->>'x4')::jsonb->'y1')
with ordinality arr(x,index)
where x->>'id'='RO'
)
update table set field=
field #- zd.path
from zd
Best regards,
Bjarni
来源:https://stackoverflow.com/questions/59344017/delete-objects-inside-nested-jsonb-arrays-with-postgresql