jsonb_set:如何在 jsonb 字段中设置数字而不是字符串值?

Mar*_*ius 2 postgresql json

在 Postgres 中,如何在 jsonb 字段中设置数字而不是字符串值?

jsonb_set想要一个 jsonb 值作为第三个参数,但数字不能转换为 json。示例代码:

CREATE OR REPLACE FUNCTION update_age(person jsonb)
  RETURNS jsonb
  LANGUAGE plpgsql AS  -- language declaration required
$func$
DECLARE
  age NUMERIC;
BEGIN
    RAISE NOTICE 'input %', person::TEXT;
    age := (person->'age')::NUMERIC + 1;
    RAISE NOTICE 'new age %', age;


    -- person := jsonb_set(person, '{age}', age); 
    -- this fails: function jsonb_set(jsonb, unknown, numeric) does not exist
    -- how to set a number, not string, value in the 'age' jsonb field?

    RETURN person;
END
$func$;

SELECT update_age('{"name": "John", "age": 30}');
-- desired result: {"name": "John", "age": 31}
-- not {"name": "John", "age": "31"}

Run Code Online (Sandbox Code Playgroud)

小智 10

第三个参数jsonb_set()必须是 jsonb 值。要将数字转换为正确的 jsonb 值,请使用to_jsonb(),而不是强制转换。

person := jsonb_set(person, '{age}', to_jsonb(age)); 
Run Code Online (Sandbox Code Playgroud)

不过,函数language sql会更有效:

CREATE OR REPLACE FUNCTION update_age(person jsonb)
  RETURNS jsonb
  LANGUAGE sql 
AS
$func$
  select jsonb_set(person, '{age}', to_jsonb((person ->> 'age'):: numeric + 1));
$func$
immutable;
Run Code Online (Sandbox Code Playgroud)