0

Try to make the following SQL query using the node mysql2 package:

SELECT name, someObject->>"$.foo" as slice
FROM someTable;

The table someTable has 2 columns: name, a varchar; and someObject, a JSON column.

Imagine at least one row exists like this:

name      someObject
==========================
John      { "foo": "bar" }

The expected result of the query is:

name      slice
==========================
John      bar

Simply doing this works:

const result = await connection.query('SELECT name, someObject->>"$.foo" as slice FROM someTable');

However, I need the foo value escaped as it is user input. How to properly escape this?

1 Answer 1

1

Writing the question, I figured out the answer. Hopefully this can be helpful to others.

Considering the column / slice string: someObject->>"$.foo"

The answer is: Treat the column portion (someObject) as a column, and treat the string portion ($.foo) as a string.

So to escape it properly do this:

const columnName = "someObject";
const sliceName = "$.foo";

const sql = 'SELECT name, ??->>? as slice FROM someTable';
const values = [columnName, sliceName];
const result = await connection.query(sql, values);
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.