0

So im trying to pass a JSON in a Query to save in the Database. But i can't figure out how to escape that single quote mark at "Don't". I've tried \' but i still can't pass it.

pgClient.query(`INSERT INTO data VALUES(83, '{ "name": "John Doe", "items": ["Don't", "Drink"] }')`)

Note: I've used the ` quote since i was passing the JSON as an object.

notjordi
  • 11
  • 2
  • look at this example https://stackoverflow.com/a/1586588/18278998 – Roe Oct 25 '22 at 09:41
  • 1
    Don't write strings containing strings containing strings. We'll all get headaches. Use parametrised queries instead. – Quentin Oct 25 '22 at 09:42
  • In one of my projects I have `const sql = 'INSERT INTO user_data VALUES($1, $2)'; const result = await client.query(sql, [userId, data]);` where `data` is a User *object*. The conversion to JSON is all taken care of by the API. (the `data` column is defined as `data jsonb`) – Quentin Oct 25 '22 at 09:55
  • 1
    @rbdeenk worked, parametrised queries is the way – notjordi Oct 25 '22 at 10:16
  • completely agree, parameterized queries also decrease the chance of SQL injection. – Roe Oct 25 '22 at 10:24

0 Answers0