Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to parse a stringified array containing HTML

This may be a silly question but I invested more than half an hour to understand why it is not working. I have a 2D javascript array. Some of the elements in array are HTMl having anchor tag with href attributes. I am trying to used JSON.parse("stringified2D array here") but it give me error as shown in this screenshot.

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

It gives me error

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

Error Screenshot

like image 581
Waqar Ahmad Avatar asked Dec 17 '25 19:12

Waqar Ahmad


2 Answers

You should escape the quotes twice \\"

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
like image 144
Tarek Deeb Avatar answered Dec 19 '25 09:12

Tarek Deeb


You need another \ to escape double quotes in string:

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"]]');
like image 21
Harry Avatar answered Dec 19 '25 09:12

Harry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!