3

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

3
  • 2
    that isn't a proper json format Commented Aug 8, 2018 at 8:12
  • 1
    this is a stringified array. And yes, an array can be be stringified and then parsed. Check here imgur.com/PnU1oUB Commented Aug 8, 2018 at 8:17
  • 1
    Do not generate JSON code manually. Use the language’s built-in functions (e.g. json_encode() in PHP or JSON.stringify() in JS) or corresponding ready-to-use libraries. Commented Aug 8, 2018 at 22:18

2 Answers 2

4

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
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.