Tag Archives: Object Literal

JSON and JavaScript Objects

JavaScript Object Notation (JSON) is the lightweight alternative to tag laden XML used as data exchange format. What it is, precisely, is a method of data transmission based on JavaScript’s object literal syntax.

JavaScript objects are containers which store key value pairs of attributes, functions and other objects of the following appearance:

var anObject = {
 firstProperty: 'someString',
 secondProperty: 111,
 aFunc: (parameter) {
         // some code
     };
 isJSON: false
}

JSON follows the same exact pattern:

{
  "firstProp": "someString",
  "secondProp": 222,
  "isJSON": true
}

Few items of note that distinguish between JSON and plain old JavaScript objects:

  • JSON requires that properties by enclosed in quotes, while JS Objects can do it either way.
  • JSON only contains key value pairs, no functions

Back and forth

Although not part of the language, its ubiquity means that JavaScript has helper methods to handle JSON. Most common function is to convert from an object literal to JSON and vice versa:

///////////////////////////////
// Object literal to JSON
///////////////////////////////
var myObject = {
   firstProp: "someString",
   secondProp: 222
}

var JSONresult = JSON.stringify(myObject); 
// Result
//  {"firstProp": "someString", "secondProp": 222 }

///////////////////////////////
// JSON to Object literal 
///////////////////////////////
JSON.parse(JSONResult);
// result
// { firstProp: "someString", secondProp: 222 }

So although similar, JS objects and JSON are not the same. In essence JS objects is how you might be normally at home, relaxed and casual versus while JSON is like being in public with more formalised rules.