4

I have strings representing jsons where field names and values are enclosed in single quotes, for example {'name': 'Grzegorz', 'age': 123}. Let's assume that I have also a table in postgres database:

CREATE TABLE item (
     metadata jsonb
);

I'm trying to insert rows using JOOQ. JOOQ generates the following statement: insert into Item values('{''name'': ''Grzegorz'', ''age'': 123}'::jsonb); but an error is thrown:

ERROR:  invalid input syntax for type json
LINE 1: insert into Item values('{''name'': ''Grzegorz'', ''age'': 1...
Token "'" is invalid.
JSON data, line 1: {'...

Is there any possibility to insert json with names enclosed in single quotes ' instead of double quotes " or should I convert all ' to "?

Thanks in advance!

Grzegorz

1
  • 1
    {'name': 'Grzegorz', 'age': 123} can be a valid javascript value, but not a valid JSON. Blindly converting all ' to " could be dangerous, just consider f.ex. {'name': 'Gregor "Grzegorz"', 'age': 123} (if that's a possible generated value, because that's too could be parsed with javascript). Instead, I would look into how these values are generated & search for a method to generate valid JSON values. Commented Nov 25, 2015 at 14:33

1 Answer 1

5

Json syntax requires double quotes, so It is not a question of Postgres. Server accepts only valid json values.

You can use replace():

insert into item 
values(replace('{''name'': ''Grzegorz'', ''age'': 123}', '''', '"')::jsonb);

select * from item;

             metadata             
----------------------------------
 {"age": 123, "name": "Grzegorz"}
(1 row)
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.