Postgres:如何将 JSONB 值转换为数字

Postgres: How to casting JSONB value to numeric

我在转换 jsonb 值时遇到问题。并且希望得到一些指导。

我们想要实现的是一些数据以字符串形式传入,我们希望将其转换为数字。

考虑以下更新语句:

update customer
set traits = jsonb_set(traits, '{arr}',traits->'arr'::text::integer)
where jsonb_typeof(traits->'arr') = 'string'
  and traits->'arr' is not null

我们目前收到以下错误:

[22P02] ERROR: invalid input syntax for type integer: "arr"

我已经尝试了各种施法咒语,但无法解决这个问题。

谁能为我们指明前进的道路?!


工作解决方案如下所示:

update customer
set traits = jsonb_set(traits, '{arr}',(traits->>'arr')::integer::text::jsonb)
where jsonb_typeof(traits->'arr') = 'string'
  and traits->'arr' is not null

三连投。有点臭

问题是你的表情

traits->'arr'::text::integer

被评估为

traits->('arr'::text::integer)

试图将 'arr' 转换为整数(由于明显的原因,您提到的错误消息失败了)。相反,你想要

(traits->'arr')::text::integer
-- or
(traits->>'arr')::integer