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"
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>
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);
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);
A simple way to make the JSON 1 line tall is to do JSON.stringify(json) at the browser's console.
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);