简体   繁体   English

我想在 JSON.stringify() 之后播放 htmlDecode

[英]I want to play htmlDecode after JSON.stringify()

I want to parse string having quotes in value into JSON.我想将带有引号的字符串解析为 JSON。

After the string of JSON.stringify() is htmlDecode(), the quot; JSON.stringify() 的字符串是 htmlDecode() 之后的 quot; is converted to " and an error occurs when JSON.parse().转换为 " 并在 JSON.parse() 时发生错误。

new DOMParser().parseFromString(input, "text/html");新的 DOMParser().parseFromString(input, "text/html"); during the process Can it be executed except "quot;"过程中除了“quot;”外是否可以执行

Or is there another way?或者还有其他方法吗?

  <script>
    const str = "&lt ;h3&gt ;&amp ;&amp ;&amp ;&quot ;&quot ;xx;;&lt ;/h3&gt ; &lt ;h2&gt ;";
    const obj = { "test1": "&lt ;h3&gt ;&amp ;&amp ;&amp ;&quot ;&quot ;xx;;&l t;/h3&gt ; &lt ;h2&gt ; ", "test2": "help" };

    function htmlDecode(input) {
      var doc = new DOMParser().parseFromString(input, "text/html");
      return doc.documentElement.textContent;
    }

    console.log(htmlDecode(str))    // <h3>&&&""xx;;</h3> <h2>
    console.log(htmlDecode(JSON.stringify(obj)))  // {"test1":"<h3>&&&""xx;;</h3> <h2> ","test2":"help"}
    console.log(JSON.parse(htmlDecode(JSON.stringify(obj)))) // VM49:1 Uncaught SyntaxError: Unexpected string in JSON at position 18 at JSON.parse (<anonymous>)
  </script>
</body>

If string does not include qout;如果字符串不包含 qout; JSON Parsing is wokring well. JSON 解析运行良好。

const quotIsNotObj = { "test1": "&lt ;h3&gt ;&amp ;&amp ;&amp ;xx;;&lt ;/h3&gt ; &lt ;h2&gt ; ", "test2": "help" };

console.log(JSON.parse(htmlDecode(JSON.stringify(successObj)))) // {"test1":"<h3>&&&xx;;</h3> <h2> ","test2":"help"} 

You can Escape String Included in object.您可以转义包含在对象中的字符串。 And That will parse Into JSON.这将解析为 JSON。

 const str = "&lt;h3&gt;&amp;&amp;&amp;&quot;&quot;xx;;&lt;/h3&gt; &lt;h2&gt;"; const obj = { 'test1': '&lt;h3&gt;&amp;&amp;&amp;&quot;&quot;xx;;&lt;/h3&gt; &lt;h2&gt; ', 'test2': 'help'}; console.log(htmlDecode(str)) // <h3>&&&""xx;;</h3> <h2> console.log(htmlDecode(JSON.stringify(obj))) // {"test1":"<h3>&&&""xx;;</h3> <h2> ","test2":"help"} //Creating New Object With Escaped String var newObj={}; Object.keys(obj).forEach(function(key){ var newVal=escapeString(htmlDecode(obj[key])); newObj[key]=newVal; }); console.log(newObj); function htmlDecode(input) { var doc = new DOMParser().parseFromString(input, "text/html"); return doc.documentElement.textContent; } //To Escape Characters like Quote function escapeString(jsonStr){ return jsonStr.replace(/\\\\n/g, "\\\\n") .replace(/\\\\'/g, "\\\\'") .replace(/\\\\"/g, '\\\\"') .replace(/\\\\&/g, "\\\\&") .replace(/\\\\r/g, "\\\\r") .replace(/\\\\t/g, "\\\\t") .replace(/\\\\b/g, "\\\\b") .replace(/\\\\f/g, "\\\\f"); }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM