skip to Main Content

I obtained the following as the output of a call to JSON.stringify:

"<?xml version="1.0" encoding="UTF-8"?>n<html>n  <head>n    <meta charset="utf-8"/>n  </head>n  <body>n    <ul id="BcVWDENh">n      <li id="3C">n        <p>Hello World</p>n      </li>n    </ul>n  </body>n</html>n"

Then, I tried to call JSON parse to obtain a JS string:

JSON.parse(
    ""<?xml version="1.0" encoding="UTF-8"?>n<html>n  <head>n    <meta charset="utf-8"/>n  </head>n  <body>n    <ul id="BcVWDENh">n      <li id="3C">n        <p>Hello World</p>n      </li>n    </ul>n  </body>n</html>n""
)

(I had to add double quotes around the content, and escape both)

and I get:

Error: SyntaxError: JSON Parse error: Unable to parse JSON string (-2700)

What’s happening here ?

2

Answers


  1. Check the output here-

    const myDefinedStr = "<?xml version="1.0" encoding="UTF-8"?>n<html>n  <head>n    <meta charset="utf-8"/>n  </head>n  <body>n    <ul id="BcVWDENh">n      <li id="3C">n        <p>Hello World</p>n      </li>n    </ul>n  </body>n</html>n";
    
    const result = JSON.parse(JSON.stringify(myDefinedStr));
    
    console.log(result);
    Login or Signup to reply.
  2. What you call the "output of a call to JSON.stringify" is actually a printout of the output. When you want to feed this string into JSON.parse, you must double all backslashes:

    document.querySelector("textarea").textContent = JSON.parse('"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<html>\n  <head>\n    <meta charset=\"utf-8\"/>\n  </head>\n  <body>\n    <ul id=\"BcVWDENh\">\n      <li id=\"3C\">\n        <p>Hello World</p>\n      </li>\n    </ul>\n  </body>\n</html>\n"');
    <textarea rows="10" cols="40"></textarea>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search