我需要以某种方式从json转换为int。我做了这个功能。:
CREATE OR REPLACE FUNCTION json2int(p_json json)
RETURNS integer AS
$BODY$DECLARE
v_json json;
--v_char character varying;
v_int integer;
BEGIN
SELECT p_json->'additionalData'->'id' INTO v_json;
--SELECT CAST(v_json as character varying) INTO v_char;
SELECT CAST(v_json as integer) INTO v_int;
RETURN v_int;
END;$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
ALTER FUNCTION json2int(json)
OWNER TO postgres;
我尝试从json转换为int,但这不起作用。然后我尝试从json转换为变为int的字符,这也没有用。所以我补充道:
CREATE CAST (json AS integer) WITH INOUT as implicit;
现在当我运行我的功能时:
SELECT json2int('{"additionalData":{"id":"4","userType":"viewer"},"type":"wall"}');
我收到此错误:
ERROR: invalid input syntax for integer: ""4""
CONTEXT: SQL statement "SELECT CAST(v_json as integer)"
PL/pgSQL function json2int(json) line 8 at SQL statement
有人可以帮忙吗?
答案 0 :(得分:3)
正如评论中所暗示的,使用->>
将文本转换为int:
SELECT (p_json -> 'additionalData' ->> 'id')::int INTO v_int;