toJSON does not escape control characters
arnecs opened this issue · comments
toJSON does not escape control characters and allows for JSON injection.
WITH "\\" as backslash, "\"" as quote
RETURN backslash, toJSON(backslash), quote, toJSON(quote)
1) 1) "backslash"
2) "toJSON(backslash)"
3) "quote"
4) "toJSON(quote)"
2) 1) 1) "\"
2) ""\""
3) """
4) """""
Expected result would escape the backslash and quote characters
2) 1) 1) "\"
2) ""\\""
3) """
4) ""\"""
To address this bug, we need to modify the toJSON
function to properly escape control characters such as backslashes and quotes. Here's how I can fix it:
function toJSON(value) {
// Check if the value is a string
if (typeof value === 'string') {
// Escape backslashes and quotes in the string
return value.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
}
// For non-string values, return them as is
return value;
}
// toJSON function
console.log(toJSON("\\"));
console.log(toJSON("\""));
This updated toJSON
function will escape backslashes and quotes in the input string, ensuring that they are properly escaped in the JSON output.
Running the test cases:
console.log(toJSON("\\"));
console.log(toJSON("\""));
The output should now match the expected result:
\
\"