Escape string in eval context with JSON.stringify

谁说我不能喝 提交于 2021-01-07 02:40:58

问题


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:


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.



来源:https://stackoverflow.com/questions/64820816/escape-string-in-eval-context-with-json-stringify

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!