0

I have a JSON which comes with single quote for one of the fields like below. A function with JSON as Input parameter is created and be called directly from the application. I would have used regexp_replace at least if it is read into the function.

for ex:

select '{
  "phrase": "foo",
  "phrase_1": "'bar'"
  }' :: json 

syntax error at or near "'"

  }'"
LINE 3:   "phrase_1": "'bar'"

The output of this is an error. so my actual problem is this json is directly read into my function.

create or replace function f_n(in json) -- it is failing to read here
returns text
---
---
end;
$$

so what is that I can do here to avoid such problem in postgresql?

1 Answer 1

3

Single quotes need to be duplicate in SQL to escape them:

select '{
  "phrase": "foo",
  "phrase_1": "''bar''"
  }'::json;

alternatively use Postgres' dollar quoting to avoid that:

select $j${
  "phrase": "foo",
  "phrase_1": "'bar'"
  }$j$::json;

When passing that as an argument to a function, this works the same:

select f_n('{
  "phrase": "foo",
  "phrase_1": "''bar''"
  }'::json);

or

select f_n($j${
      "phrase": "foo",
      "phrase_1": "'bar'"
      }$j$::json);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.