1

I'm new to postgres-node. Coming from a mySQL background, I'm unlearning old habits and now learning new things. I want to prevent SQL injections when inserting data. I read about parameterized query. Is this applicable to JSON type? I'm doing CRUD operations on a table in postgres that only have 2 columns. I'm manipulating JSON data (SELECT, INSERT and UPDATE). How do you prevent SQL injections when inserting JSON data in a table?

table

id | info
1  | { "customer": "John Doe", "items": {"product": "Beer","qty": 6}}'
2  | { "customer": "Lily Bush", "items": {"product": "Diaper","qty": 24}}

query

INSERT INTO orders (info)
VALUES('{ "customer": "Josh William", "items": {"product": "Toy Car","qty": 1}}')
1
  • There is no SQL injection hazard in the INSERT statement you quote. Perhaps you should show the code that creates the statement. Commented Apr 26, 2021 at 6:06

1 Answer 1

1

JSON type is no different from other types for injection prevention:

// totally wrong: concatenated unsafe input straight into the query
client.query(`INSERT INTO orders (info) VALUES (${allegedlyJsonStringifiedUserInput})`);
// totally right: parameterized query, delegating injection safeties to pg
client.query(`INSERT INTO orders (info) VALUES ($1)`, [allegedlyJsonStringifiedUserInput]);
Sign up to request clarification or add additional context in comments.

1 Comment

Okay thanks man. I wasn't sure. I'm just inserting the whole json object as this one big value in the parameterized query haha makes my life easier. Cheers!

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.