首页 > 解决方案 > 无法解析包含 HTML 的字符串化数组

问题描述

这可能是一个愚蠢的问题,但我花了半个多小时来了解它为什么不起作用。我有一个 2D javascript 数组。数组中的一些元素是 HTMl,具有带 href 属性的锚标记。我正在尝试使用JSON.parse("stringified2D array here"),但它给了我错误,如此屏幕截图所示。

var cd = JSON.parse('[["header","This is some header"],["footer","<p>This addon is brough to you by <a href=\"https://www.accemy.com\">Accemy</a> and <a href=\"swgapps.com\">SW gApps</a></p>This is universal and appended to all add-on content"],["nslookup","NS Lookup allows to fetch DNS records from public DNS servers"]]');

它给了我错误

Uncaught SyntaxError: Unexpected token h in JSON at position 88
    at JSON.parse (<anonymous>)
    at <anonymous>:1:15

错误截图

标签: javascriptjsonparsing

解决方案


你应该两次转义引号\\"

var s = '[' +
  '["header","This is some header"],' +
  '["footer","<p>This addon is brough to you by ' +
  '<a href=\\"https://www.accemy.com\\">Accemy</a> and ' + //here
  '<a href=\\"swgapps.com\\">SW gApps</a></p>' + //and here
  'This is universal and appended to all add-on content"],' +
  '["nslookup","NS Lookup allows to fetch DNS records from public DNS servers"]]';

var cd = JSON.parse(s);

console.log(cd.length); //3

推荐阅读