javascriptjson

Working with nested JSON object gives me console error


Working with a JSON nested object and I get an error when running in the javascript console "JSON3.html:11 Uncaught SyntaxError: Invalid or unexpected token"

enter image description here

I've verified the JSON via https://jsonformatter.org/json-viewer and that looks ok. The output is only the text in my h2 tag. What am I missing? Here's the code.

<!DOCTYPE html>
<html>
<body>

<h2>Testing JSON .</h2>

<p id="demo"></p>

<script>

var myJSON = '{
  "LevelOne": {
    "LevelTwo": {
      "location": {
        "campus": "SouthWest",
        "building": "Biggest",
        "floor": "1st",
        "room": "101"
      },
      "quantity": "1",
      "section": "ABC",
      "task": "abc123456zyx"
    }
  }
}';
var myObj = JSON.parse(myJSON);
document.getElementById("demo").innerHTML = myJSON.LevelOne.LevelTwo.location;
</script>

</body>
</html>

Solution

  • String concatenation

    String that are surrounding using " and ' cannot extend over multiple lines, so have to separate each line and then concatenate them. Example:

    var myJSON = '{' +
      '"LevelOne": {' +
        '"LevelTwo": {' +
          '"location": {' +
            '"campus": "SouthWest",' +
            '"building": "Biggest",' +
            '"floor": "1st",' +
            '"room": "101"' +
          '},' +
          '"quantity": "1",' +
         '"section": "ABC",' +
          '"task": "abc123456zyx"' +
        '}' +
      '}' +
    '}';
    
    console.log(myJSON);

    Template Literals

    In ES6, template literals were added, that allow to have strings span through multiple lines, provided you use ` instead of " or '. Example:

    var myJSON = `{
      "LevelOne": {
        "LevelTwo": {
          "location": {
            "campus": "SouthWest",
            "building": "Biggest",
            "floor": "1st",
            "room": "101"
          },
          "quantity": "1",
          "section": "ABC",
          "task": "abc123456zyx"
        }
      }
    }`;
    
    console.log(myJSON);

    Removes the new lines from the JSON

    A simple way to make the JSON 1 line tall is to do JSON.stringify(json) at the browser's console.

    Use a normal JSON

    You can just use the normal object notation of the JSON instead of the JSON and then if you want to you can convert it back to a string using JSON.stringify. Example:

    var myJSON = {
      "LevelOne": {
        "LevelTwo": {
          "location": {
            "campus": "SouthWest",
            "building": "Biggest",
            "floor": "1st",
            "room": "101"
          },
          "quantity": "1",
          "section": "ABC",
          "task": "abc123456zyx"
        }
      }
    };
    
    console.log(JSON.stringify(myJSON));
    console.log(myJSON);