Home > Software engineering >  Problem with JSON.stringify a tag outerHTML in multidimensional array
Problem with JSON.stringify a tag outerHTML in multidimensional array

Time:10-16

I'm trying to stringify a multidimensional array with some string and the outerHTML of an anchor tag. For some unknown (to me) reason, it adds a double \ to the outerHTML text resulting in invalid JSON.

const a = document.getElementByTagName('a')[0].outerHTML;
const array = [["a", a],["b", a],["c", a]];
const json = JSON.stringify(array);

The result is:

'[["a","<a href=\\"https://www.google.com/\\" target=\\"_blank\\" rel=\\"noopener noreferrer\\">Link</a>"], 
["b","<a href=\\"https://www.google.com/\\" target=\\"_blank\\" rel=\\"noopener noreferrer\\">Link</a>"], 
["c","<a href=\\"https://www.google.com/\\" target=\\"_blank\\" rel=\\"noopener noreferrer\\">Link</a>"]]'

CodePudding user response:

I think it happened because of the Escape Sequence. See a ecmascript link for details.

CodePudding user response:

you need to console.log it

from experience, I can tell that you just copied this string from your dev console, after letting it debug-print the contents of that JSON Serialization.

  • Related