Oracle 19c使用apex_json生成JSON时如何保留值为null的列
解决方案
核心原因是APEX_JSON的write方法默认省略值为NULL的列,你可以通过以下两种方式实现需求:
方法1:修改游标查询(最通用,可直接输出空字符串)
在查询层用NVL函数将可能为NULL的字段替换为空字符串,从根源上避免NULL值出现,兼容性最好,所有APEX版本都支持。
修改后的存储过程示例:
create or replace procedure my_demo as l_cur sys_refcursor; begin open l_cur for select name, email, nvl(phonenumber, '') as phonenumber -- NULL转空字符串 from temp order by name; apex_json.open_object; apex_json.write('data', l_cur); apex_json.close_object; end my_demo;
方法2:启用write方法的NULL输出参数
APEX 5.1及以上版本中,apex_json.write处理游标时支持p_write_nulls参数,设置为true时会自动保留NULL值列,输出JSON标准的null值。
修改后的写入代码示例:
apex_json.open_object; -- 新增p_write_nulls参数 apex_json.write(p_name => 'data', p_value => l_cur, p_write_nulls => true); apex_json.close_object;
注:该方法输出的NULL列格式为
"phonenumber": null,如果需要空字符串占位,还是建议使用方法1。
可选方案:使用Oracle原生SQL/JSON生成(性能更优)
Oracle 12cR2及以上版本(包括你使用的19c)支持原生SQL/JSON函数,不需要依赖APEX_JSON包,性能更高,也可以灵活控制NULL值输出:
create or replace procedure my_demo as l_json clob; begin select json_object( 'data' value json_arrayagg( json_object( 'name' value name, 'email' value email, 'phonenumber' value nvl(phonenumber, ''), null on null -- 不需要转空字符串时可以去掉NVL,仅保留这个参数输出JSON null ) ) ) into l_json from temp; -- 输出JSON htp.prn(l_json); end my_demo;
内容的提问来源于stack exchange,提问作者dnraikes
相关产品推荐
相关产品推荐

