PostgreSQL13动态构造jsonb_set路径报数组格式错误如何解决
问题原因
你报错的核心是混淆了SQL数组构造语法和PostgreSQL数组字面量格式:
- 硬编码写法里的
ARRAY['userProfile','0','DocumentDetails']是PostgreSQL原生的数组构造语法,执行时会直接生成text[]类型的路径参数,符合jsonb_set的参数要求。 - 你动态拼接的是
ARRAY['userProfile','0','DocumentDetails']这段字符串,要转成text[]类型时,PostgreSQL要求数组字面量必须以{开头,比如{userProfile,0,DocumentDetails}才是合法的数组字面量格式,带ARRAY关键字的字符串不属于合法的数组字面量,因此触发格式错误。
另外你错误写法的WITH子查询中还有笔误:jsonb_array_elements(user_details->'Profile')里的键名少了user前缀,和你硬编码写法里的userProfile不一致,也需要修正。
修正方案
直接用原生数组构造语法组装路径参数即可,不需要手动拼接字符串:
with whatposition as ( select position pos from users cross join lateral jsonb_array_elements(user_details->'userProfile') with ordinality arr(elem,position) where display_ok=false ) update users set user_details=jsonb_set( user_details, -- 直接用ARRAY构造动态参数,不要拼接字符串再强转 ARRAY['userProfile', (select pos-1 from whatposition)::text, 'DocumentDetails'], '[{"y":"supernewValue"}]' ) where display_ok=false;
如果确实需要通过字符串拼接构造数组,要按数组字面量格式拼接:
-- 仅做示例,更推荐上方直接构造数组的写法 concat('{userProfile,', (select pos-1 from whatposition)::text, ',DocumentDetails}')::text[]
内容的提问来源于stack exchange,提问作者tenet testuser1
相关产品推荐
相关产品推荐

