表public.challenge
,列行
JSONB
我的初始 JSON lines
:
[
{
"line": 1,
"blocs": [
{
"size": 100,
"name": "abc"
},
{
"size": 100,
"name": "def"
},
{
"size": 100,
"name": "ghi"
}
]
},
{
"line": 2,
"blocs": [
{
"size": 100,
"name": "xyz"
}
]
}
]
期望的结果(为每个bloc
添加一个新对象wrapper
):
[
{
"line": 1,
"blocs": [
{
"size": 100,
"name": "abc",
"wrapper": {
"nestedName": "abc",
"type": "regular"
}
},
{
"size": 100,
"name": "def",
"wrapper": {
"nestedName": "def",
"type": "regular"
}
},
{
"size": 100,
"name": "ghi",
"wrapper": {
"nestedName": "ghi",
"type": "regular"
}
}
]
},
{
"line": 2,
"blocs": [
{
"size": 100,
"name": "xyz",
"wrapper": {
"nestedName": "xyz",
"type": "regular"
}
}
]
}
]
我有以下查询(来自 here ):
WITH cte AS (
SELECT id_lines,
jsonb_agg(
jsonb_set(val1, '{blocs}',
(
SELECT jsonb_agg(arr2 ||
json_build_object(
'wrapper', json_build_object('nestedName', arr2->'name', 'type', 'regular')
)::jsonb
)
FROM jsonb_array_elements(arr1.val1->'blocs') arr2
WHERE arr2->'name' IS NOT NULL
)
))
FROM public.challenge, jsonb_array_elements(lines) arr1(val1)
GROUP BY 1
)
UPDATE public.challenge SET lines=(cte.jsonb_agg) FROM cte
WHERE public.challenge.id_lines=cte.id_lines;
条件WHERE arr2->'name' IS NOT NULL
不会过滤掉name为null的 block ,我很难找出原因..谢谢!
最佳答案
您必须区分 SQL NULL 和 JSON null
。
IS NOT NULL
谓词测试 SQL NULL,这意味着该属性不存在于 JSON 中。
要测试 JSON null
,请使用
WHERE arr2->'name' <> 'null'::jsonb
类型转换为 jsonb
是不必要的,并且会隐式执行。
关于Postgresql 和 jsonb : WHERE <a specific nested field in my json> IS NOT NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68015588/