You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何检测JSON中未传递或为null的必填键?求更简便实现方案

更简洁的PostgreSQL方法返回JSON缺失的必填键

这里提供几种比你当前实现更直接的方式,核心思路都是简化必填键与JSON现有键的对比逻辑:

方案1:数组遍历+存在性检查

直接遍历必填键数组,过滤出不存在于JSON中的键,最后拼接成字符串:

declare
    obl_arr   text[] := array['key a', 'key b', 'key c', 'key d'];
    f_json    jsonb := jsonb_strip_nulls(inp_json::jsonb);
begin
    return array_to_string(
        array(
            select key 
            from unnest(obl_arr) as key
            where not jsonb_exists(f_json, key)
        ),
        ','
    );
end;

逻辑清晰,避免了嵌套子查询,直接通过jsonb_exists判断键是否存在(jsonb_strip_nulls已剔除值为null的键,所以不存在的就是缺失项)。

方案2:简化集合过滤

保留你原有的string_agg逻辑,但把except替换为更直观的not in判断:

declare
    obl_arr   text[] := array['key a', 'key b', 'key c', 'key d'];
    f_json    jsonb := jsonb_strip_nulls(inp_json::jsonb);
begin
    return (
        select string_agg(key, ',' order by key)
        from unnest(obl_arr) as key
        where key not in (select jsonb_object_keys(f_json))
    );
end;

减少了一层子查询嵌套,代码更紧凑,可读性更强。

方案3:利用JSONB差集操作(PostgreSQL 12+)

如果必填键固定,可以将其转为JSONB对象,通过差集运算符-直接获取缺失的键:

declare
    obl_jsonb jsonb := '{"key a":null, "key b":null, "key c":null, "key d":null}'::jsonb;
    f_json    jsonb := jsonb_strip_nulls(inp_json::jsonb);
begin
    return array_to_string(
        array(select jsonb_object_keys(obl_jsonb - f_json)),
        ','
    );
end;

obl_jsonb - f_json会返回必填键对象中存在但输入JSON中不存在的键值对,直接提取这些键即可,代码最简洁。

内容的提问来源于stack exchange,提问作者Oleh Sydor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 21:45:34