Escape string in eval context with JSON.stringify

前端 未结 1 914
旧巷少年郎
旧巷少年郎 2021-01-29 00:06

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 demonstrat

相关标签:
1条回答
  • 2021-01-29 00:45

    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.

    0 讨论(0)
提交回复
热议问题