Single quote in JSON field POSTGRESQL

Za7pi picture Za7pi · Dec 29, 2015 · Viewed 8.5k times · Source

I am trying to manipulate a JSON with a single quote inside, and I am having some troubles:

1.- When I have a function, I cant pass as parameter a JSON string with a single quote inside: This is the function:

CREATE OR REPLACE FUNCTION public.give_me_text
(
  IN  text  json
)
RETURNS JSON AS
$$
DECLARE
v_text   varchar;
begin

RAISE NOTICE 'text: %', text;
v_text:=text || '- hello';
return v_text;
end
$$
LANGUAGE 'plpgsql';

By calling like this is working:

SELECT * FROM give_me_text
(
'{"es":"name 1","en":"name 2","de":"name 3","fr":"name 4","pt":"name 5"}'
);

But when I have got a single quote is not working:

SELECT * FROM give_me_text
    (
    '{"es":"nam'e 1","en":"name 2","de":"name 3","fr":"name 4","pt":"name 5"}'
    );

2.- When I am tryhing to insert JSON value with Single quote inside, it is giving me the same error: This is working:

INSERT INTO public.my_columns VALUES ('{ "name": "Book the First", "author": { "first_name": "Bob", "last_name": "White" } }');

But this is not working:

INSERT INTO public.my_columns VALUES ('{ "name": "Book's the First", "author": { "first_name": "Bob", "last_name": "White" } }');

Any ideas how to escape this single quote? Thanks

Answer

Andomar picture Andomar · Dec 29, 2015

In SQL, single quote must be escaped in a string. This is not a valid string:

'{"es":"nam'e 1"}'

because the string ends after "nam. You can escape the single quote by repeating it:

'{"es":"nam''e 1"}'

If you're doing dynamic SQL, you can pass parameters to execute:

execute 'insert into YourTable (col1) values ($1);' using json_var;