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

标签 javascript html json dom

我想将包含引号的字符串解析为 JSON。

JSON.stringify()的字符串在htmlDecode()之后,“”转换为 "并且在 JSON.parse() 时发生错误。

new DOMParser().parseFromString(input, "text/html");过程中 除了“quot;”以外还能执行吗

或者还有其他方法吗?

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

如果字符串不包含qout; 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"} 

最佳答案

您可以转义对象中包含的字符串。这将解析成 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");
 }

关于javascript - 我想在 JSON.stringify() 之后播放 htmlDecode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57583772/

相关文章:

java - 如何从套接字读取 JSON 数据而不是一行?

javascript - 无法从已解析的 JSON 中记录对象详细信息?

javascript - 三.js如何用mousedown事件画线

javascript - 路由在 Node.js 中不起作用

php - 单击下拉列表时,站点中出现水平滚动

javascript - 我如何使用 jQuery 删除除特定类之外的所有 div 和其他 DOM HTML 元素

javascript - 最高效的阵列洗牌器

0 :0:0. 0 格式的 JavaScript 计时器计数不正确

jquery - 如何创建垂直时间轴

json - 在 Azure JSON 模板中创建 CustomScript 的正确方法