[英]How to delete JSON Object from JSON array in Postgres?
I am new to Postgres.我是 Postgres 的新手。 I want to delete the JSON object from the JSON array.
我想从 JSON 数组中删除 JSON 对象。
I have a table where I am using jsonb column in that I am storing JSON array as like below.我有一个表,我在其中使用 jsonb 列,因为我正在存储 JSON 数组,如下所示。
[
{
"id": "c75e7a-001e-4d64-9613-62f666d42103",
"name": "Product1"
},
{
"id": "c75e7a-001e-4d64-9613-62f666d42103",
"name": null
},
{
"id": "c75e7a-001e-4d64-9613-62f666d42103",
"name": "Product2"
},
{
"id": "c75e7a-001e-4d64-9613-62f666d42103",
"name": null
}
]
I want to remove JSON objects from an array that contains a null value in the name key.我想从名称键中包含空值的数组中删除 JSON 对象。
after removing answer should be like this删除答案后应该是这样的
[
{
"id": "c75e7a-001e-4d64-9613-62f666d42103",
"name": "Product1"
},
{
"id": "c75e7a-001e-4d64-9613-62f666d42103",
"name": "Product2"
}
]
anyone, please help me to write the SQL query,任何人,请帮我编写 SQL 查询,
I know how to get all the records from the table which contains the null value.我知道如何从包含空值的表中获取所有记录。
SELECT *
FROM table_name
WHERE jsonb_col_name @>CAST('[{"name": null}]' AS JSONB);
But I don't know how to make a delete query please help me with this.但我不知道如何进行删除查询,请帮我解决这个问题。 How Can I do it using a query?
我如何使用查询来做到这一点?
Unnest the array with jsonb_array_elements
, exclude the null
values with a FILTER
and aggregate them again eg与阵列UNNEST
jsonb_array_elements
,排除null
了值FILTER
,再比如他们聚集
SELECT
jsonb_agg(j) FILTER (WHERE j->>'name' IS NOT NULL)
FROM table_name t, jsonb_array_elements(jsonb_col) j
GROUP BY t.jsonb_col;
Demo: db<>fiddle
演示:
db<>fiddle
You can filter out by j.value ->> 'name' IS NOT NULL
after splitting the array into sub-objects by using JSONB_ARRAY_ELEMENTS
and then apply JSONB_AGG
in order to convert it back to an array such as在使用
JSONB_ARRAY_ELEMENTS
将数组拆分为子对象后,您可以通过j.value ->> 'name' IS NOT NULL
过滤掉,然后应用JSONB_AGG
以将其转换回数组,例如
SELECT JSONB_PRETTY(
JSONB_AGG(j)
)
FROM t,
JSONB_ARRAY_ELEMENTS(json_data) AS j
WHERE j.value ->> 'name' IS NOT NULL
GROUP BY json_data
If needed to update the existing data, then you might consider using如果需要更新现有数据,那么您可以考虑使用
WITH tt AS
(
SELECT JSONB_AGG(j) AS new_val,
json_data
FROM t,
JSONB_ARRAY_ELEMENTS(json_data) AS j
WHERE j.value ->> 'name' IS NOT NULL
GROUP BY json_data
)
UPDATE t
SET json_data = new_val::JSONB
FROM tt
WHERE t.json_data = tt.json_data
You can use json_array_elements
:您可以使用
json_array_elements
:
select json_agg(i.value) from json_array_elements('[{"id": "c75e7a-001e-4d64-9613-62f666d42103", "name": "Product1"}, {"id": "c75e7a-001e-4d64-9613-62f666d42103", "name": null}, {"id": "c75e7a-001e-4d64-9613-62f666d42103", "name": "Product2"}, {"id": "c75e7a-001e-4d64-9613-62f666d42103", "name": null}]') v
where (v.value -> 'name')::text != 'null'
Output:输出:
[{"id": "c75e7a-001e-4d64-9613-62f666d42103", "name": "Product1"}, {"id": "c75e7a-001e-4d64-9613-62f666d42103", "name": "Product2"}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.