The differences between JSON and JavaScript object
Both are not the same as there are differences between them. First, let me explain about JSON. It’s JavaScript Object Notation which is used to transfer the data between a browser and a server.
//JSON
{“FirstName”:”Some name”}
JSON values support the below data types
- string
- number
- object (JSON object)
- array
- boolean
- null
JSON values cannot be one of the following data types
Even there is an XML which is used to transfer the data between a browser and a server, JSON is preferred because of its lightweight nature and XML is much more difficult to parse than JSON.
JSON is parsed into a ready-to-use JavaScript object.
JavaScript Object
its a name: value pairs (name and value separated by a colon). JavaScript objects are containers for named values called properties or methods. In the javascript object, keys are not mandatory to quoted. Where in JSON its a rule for all the keys must be quoted using double quotes. In JavaScript Object, single or double quotes are not considered for values, either one can be used.
//Object literal
var obj = { wesite : “programmer first” };
var myObject = { name: 'some string value', age: 2, exists: false};
var newWebPage = {
//anarrayliteralkeywords: [
"JavaScript",
"JSON",
"JavaScript Object",
],
rank: {
//nestedobjectliterapagerank: 40,
alexarank: 300
},
onSearch: function(){
//function//codehere
}
};
Object literal value supports below data types
- Boolean
- String
- Number
- Function
- Array
- Object
- null
- undefined
Differences
The quotes are mandatory on JSON wherein the object literal keys are not mandatorily quoted. In ECMAScript, starting from ES5, reserved words may be used as object property names.
//Javascript Object
var obj = {if:"new value"};
The reserved keywords may not be used as variables, functions, methods, or object identifiers as it's not a good practice and ECMAScript specifies special behavior for them. The grammar of string changes if it’s not delimited by double quotes while in javascript object literal you can use single or double quotes interchangeably.
// Invalid JSON
{ "foo": 'bar' }
You can validate JavaScript object in your browser console like the below-mentioned screenshot
JSON can be validated in
JSON Online editor