Skip to content Skip to sidebar Skip to footer

Escape String In Eval Context With Json.stringify

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

Solution 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.

functionf(somePOJO) {
  var s = eval( JSON.stringify(JSON.stringify(somePOJO)) );
  returnJSON.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.

Post a Comment for "Escape String In Eval Context With Json.stringify"