0

First of all: I know that there are many questions related to escaping, but I did not found a generally working answer so far. Say I have this simple toy function for demonstration:

function f(somePOJO) {
  var s = eval("'" + JSON.stringify(somePOJO) + "';"); // for demonstration only
  return JSON.parse(s);
}
const clone = f({a: 1, b: "c"});

Given an object literal such as {a: 1, b: "c"} (a POJO), f should return a "clone" of it. (Note that I do not really use this approach for cloning or similar, and I am aware that eval is evil and also that it is not even needed here, it's just for demonstration of the escaping problem!)

This works fine, but only as long as the POJO values do not contain a '. Now of course I could escape the JSON by using something like JSON.stringify(somePOJO).replace(/'/g, "\\'"). This works if the POJO values contain ', but not if they contain \\'. And this creates a spiral of escaping...

Is there a solution to this at all?

1
  • Since it is a theoretical issue: stringify provides an optional second function parameter which you could use to sanitise your values. Commented Nov 13, 2020 at 12:53

1 Answer 1

1

The escape function to preserve a JSON string through being evaluated by the eval function, the JavaScript compiler under some circumstances or by the JSON.parse function is actually JSON.stringify. This JSON method will happily stringify string values, not just object data types.

function f(somePOJO) {
  var s = eval( JSON.stringify(JSON.stringify(somePOJO)) );
  return JSON.parse(s);
}
const obj = {a: 1, b: "c", d: "back\\, forward/"}
const clone = f(obj);
console.log(obj);
console.log(clone);

The reason it's not one of the escape/encodeURI/encodeURIComponent family of functions is that these are for escaping characters for inclusion in URLs whereas this case is about escaping characters to be parsed by a JavaScipt parser.

In most cases, particularly to parse JSON text using JSON.parse, stringifying JSON text a second time and parsing it twice is simply unnecessary.

Of somewhat academic interest now but before the introduction of JSON into Javascript, one could stringify a string by serially inspecting its characters and backslash escaping backslashes, at least one kind of quote marks, and unicode escaping control codes - the posted question may be missing the part about needing to escape backslash characters as well as quote marks.

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.