JSON vs JS Object

Showing the differences

by db_dev

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.5.0/knockout-min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/knockout.mapping/2.3.5/knockout.mapping.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css">
<h3>Tutorial!</h3>
<p>
	Example Code showing correct and incorrect JS Objects vs. JSON Object.
</p>

JavaScript

let jsObjVariable = "I am a variable!"

let jsObj = {
    jsBoolean: true,
    jsString: "I'm a string!",
    jsNumber: 42,
    jsNull: null,
    jsArray: ["I", "am", "an", "array"],
    jsObject: {
        jsKey: "JS Value"
    },
    jsFunction: function() {
		// My Comment is allowed
        console.log("I'm a function!");
    },
    jsVariable: jsObjVariable // My comment is allowed
};

// Call said function
let jsonObj = {
    "jsBoolean": true,
    "jsString": "I'm a string!",
    "jsNumber": 42,
    "jsNull": null,
    "jsArray": ["I", "am", "an", "array"],
    "jsObject": {
        "jsKey": "JS Value"
    }
};

/* Incorrect. You can only pass the 6 datatypes as a value */
// Check in https://jsoneditoronline.org/ for error

/*let jsonObjError = {
	 "jsFunction": function() {
        console.log("Function not allowed!");
    },
	 "jsFunction": "function() {
        console.log('Even with quotes, Function not allowed!');
    }",
	jsVariable: jsObjVariable, // Variable not allowed. Nor are comments!
	
};*/


/* How to access each data type */

//Dot Notation
console.log("---- JS-OBJ Dot Notation ----");
console.log(jsObj.jsBoolean);
console.log(jsObj.jsString);
console.log(jsObj.jsNumber);
console.log(jsObj.jsNull);
console.log(jsObj.jsArray);
console.log(jsObj.jsObject.jsKey);
jsObj.jsFunction();
console.log(jsObj.jsVariable);

// Bracket Notation
console.log("---- JS-OBJ Bracket Notation ----");
console.log(jsObj["jsBoolean"]);
console.log(jsObj["jsString"]);
console.log(jsObj["jsNumber"]);
console.log(jsObj["jsNull"]);
console.log(jsObj["jsArray"]);
console.log(jsObj["jsObject.jsKey"]);
jsObj["jsFunction"]();
console.log(jsObj["jsVariable"]);

//JSON can be accessed the same way
console.log("---- JSON-OBJ Bracket Notation ----");
console.log(jsonObj.jsBoolean);
console.log(jsonObj["jsBoolean"]);

// Parse JSON
// JSON.parse(jsonObj); // Unexpected token errors mean that the data is already parsed