【问题标题】:Unable to parse a stringified array containing HTML无法解析包含 HTML 的字符串化数组
【发布时间】:2019-01-15 10:09:36
【问题描述】:

这可能是一个愚蠢的问题,但我花了半个多小时来了解它为什么不起作用。我有一个 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

【问题讨论】:

  • 这不是正确的 json 格式
  • 这是一个字符串化数组。是的,一个数组可以被字符串化然后解析。在这里查看imgur.com/PnU1oUB
  • 不要手动生成 JSON 代码。使用语言的内置函数(例如 PHP 中的 json_encode() 或 JS 中的 JSON.stringify())或相应的即用型库。

标签: javascript json parsing


【解决方案1】:

您需要另一个\ 来转义字符串中的双引号:

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"]]');

【讨论】:

    【解决方案2】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 2020-12-14
      • 2011-12-19
      • 2012-08-09
      • 2017-11-06
      • 2013-08-31
      • 1970-01-01
      • 1970-01-01
      • 2018-10-29
      • 1970-01-01
      相关资源
      最近更新 更多