这可能是一个愚蠢的问题,但是我花了半个多小时来了解为什么它不起作用。我有一个2D JavaScript数组。数组中的某些元素是HTM1,具有带有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
答案 0 :(得分:4)
您应该两次将引号转义\\"
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
答案 1 :(得分:3)
您需要另一个\
来转义字符串中的双引号:
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"]]');