我做了一個簡單的函數來用新值更新一個jsonb:PostgreSQL的9.4 - 無效的輸入語法轉換爲JSONB
CREATE OR REPLACE FUNCTION jsonupdate(
IN "pJson" jsonb, IN "pNewValues" jsonb)
RETURNS jsonb AS
$BODY$
DECLARE
jsonreturn jsonb;
BEGIN
jsonreturn := (SELECT json_object_agg(keyval.key, keyval.value::jsonb)
FROM (SELECT key,
CASE WHEN "pNewValues" ? key THEN
(SELECT "pNewValues" ->> key)
ELSE
value
END
FROM jsonb_each_text("pJson")) keyval);
RETURN jsonreturn;
END; $BODY$
LANGUAGE plpgsql IMMUTABLE
COST 100;
樣品輸入和輸出:
IN:SELECT jsonupdate('{"a" : "1", "b" : "2"}', '{"a": "3"}');
OUT:{"a": 3, "b": 2}
IN:SELECT jsonupdate('{"a" : "3", "b" : { "c": "text", "d": 1 }}', '{"b": { "c": "another text" }}');
OUT:{"a": 3, "b": {"c": "another text"}}
IN:SELECT jsonupdate('{"a" : "1", "b" : "2", "c": 3, "d": 4}', '{"a": "5", "d": 6}');
OUT:{"a": 5, "b": 2, "c": 3, "d": 6}
使用這樣一個輸入時發生該問題:SELECT jsonupdate('{"a" : "1", "b" : ""}', '{"a": "5"}')
或者這一個:SELECT jsonupdate('{"a" : "1", "b" : "2"}', '{"a": "."}')
或這一個:SELECT jsonupdate('{"a" : "1", "b" : "2"}', '{"a": ""}')
它給了我一個錯誤
ERROR: invalid input syntax for type json DETAIL: The input string ended unexpectedly. CONTEXT: JSON data, line 1:
這裏有什麼問題?
你需要調用'jsonb_each()','不jsonb_each_text()' – pozs