0

I have stored JSON data in variable. but while retrieving its showing unexpected token o.

var somejson = "[{ \"key1\" : \"<header class=\"main-header dark-bg\"><div class=\"row\"></div></header>\"},{\"key2\" : \"<div class=\"row content clearfix worldwide dark-bg t--bg-5\"></div>\"}]";

var mainObject = JSON.parse(somejson);
  console.log(mainObject);
  for (var key in mainObject) {
    //console.log("key"+key);
          var innerObject = mainObject[key];
          //console.log("inner object "+innerObject);
          for (var innerKey in innerObject) {
            var t = innerObject[innerKey];
            console.log(t);
}
}

Can some one help me where i'm wrong, i'm gettting unexpected token o error. I searched for solution but couldn't able to resolve. please help me on this

1
  • JSON string is invalid thats what error says. Commented Apr 27, 2018 at 10:07

2 Answers 2

3

Your JSON data is invalid since you are having "main-header dark-bg" inside the value of key key1 without escaping those double quotes.

Make it

var somejson = "[{ \"key1\" : \"<header class=\\\"main-header dark-bg\\\"><div class=\\\"row\\\"></div></header>\"},{\"key2\" : \"<div class=\\\"row content clearfix worldwide dark-bg t--bg-5\\\"></div>\"}]";

Or use single quotes for attribute values inside the key value

var somejson = "[{ \"key1\" : \"<header class='main-header dark-bg'><div class='row'></div></header>\"},{\"key2\" : \"<div class='row content clearfix worldwide dark-bg t--bg-5'></div>\"}]";
Sign up to request clarification or add additional context in comments.

1 Comment

_gurvinder372 first one worked for me. Thanks for the solution.
0

Make your json as follows:

"[{ "key1" : "<header class='main-header dark-bg'><div class='row'></div></header>"},{"key2" : "<div class='row content clearfix worldwide dark-bg t--bg-5'></div>"}]"

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.