38

Can anyone tell me the difference between Javascript Object and JSON object with an example?

5 Answers 5

57

A Javascript object is a data type in Javascript - it makes sense only in Javascript. Often you see a Javascript object literal like this:

var obj = {
    a: 1,
    b: 2
};

A JSON string is a data interchange format - it is nothing more than a bunch of characters formatted a particular way (in order for different programs to communicate with each other). Because of this, it can exist inside Javascript, or in another language or simply stored inside a database or a text file.

The above Javascript object can be represented in the JSON format in Javascript like this:

var json = '{ "a": 1, "b": 2 }';

Or in C# like this:

string json = "{ \"a\": 1, \"b\": 2 }";

As you can see, a JSON is simply stored inside a string. To make it useful, the JSON string can be parsed to produce an object in any language. Because the JSON format mimics Javascript's object literal syntax, Javascript makes the parsing process easy:

var obj = eval('(' + json + ')');

Though typically you'd see:

var obj = JSON.parse(json); // for security reasons

Note that JSON is limited in that it cannot store functions - the only values it can contain are:

  • objects (literals)
  • arrays
  • numbers
  • booleans
  • strings
  • nulls
Sign up to request clarification or add additional context in comments.

1 Comment

The key difference between JSON and Javascript object is "JSON string is a data interchange format" and Javascript object is a data type in Javascript
15

JSON is a text representation of a javscript object. It is effectively an object literal in javascript notation (hence the name - JavaScript Object Notation => JSON).

If you want to "compare" two object, convert the text to objects then compare keys and values.

Some examples of objects to/from text:

// Create obj using an object literal
var obj = {key: 'value'};

// Convert to text using JSON.stringify
var text = JSON.stringify(obj);

// Show the value of text
alert( text ); // {"key":"value"}

// Create a new object from text
var newObj = JSON.parse(text); // javascript object

// Show the text version of newObj
alert(JSON.stringify(newObj));  // {"key":"value"}

// Use text as code
var newObj2 = eval('(' + text + ')');

// It is indeed a string literal
alert(JSON.stringify(newObj2));  // {"key":"value"}

If you want to compare two objects, convert them from JSON to objects (if they are JSON in the first place) then do something like:

function compareObjects(a, b) {
  var i, p, aProps = [], bProps = [];

  // Simple test first
  if (a === b) {
    return true;
  }

  // Get properties of a
  for (p in a) {
    if (a.hasOwnProperty(p)) {
      aProps.push(p);
    } 
  }

  // Get properties of b
  for (p in b ) {
    if (b.hasOwnProperty(p)) {
      bProps.push(p);
    } 
  }

  // If don't have same properties, return false
  if (aProps.sort().join('') != bProps.sort().join('')) {
    return false;
  }

  // If property values aren't the same, return false
  i = aProps.length;
  while (i--) {
    if (a[aProps[i]] !== b[bProps[i]]) {
      return false;
    }
  }

  // If passed all tests, must be equal
  return true;
}

4 Comments

yes I have read that..i do not get a declaration example of both anywhere..i want to compare them and see what's different?
Edit your question to include that.
Be aware: the "var obj =" is NOT part of JSON! Technically speaking, JSON is data-only although it tends to be executed as if it's code to load an object in memory. You only need the {} and the stuff in-between as JSON data, which you could then 'evaluate' and assign to a variable in your JavaScript code or other programming language. Adding the "var" thing turns JSON into Javascript...
@Wim - yes, good point. I was using a javascript object literal as an easy way to get a properly formatted JSON string.
3

JSON stands for "JavaScript Object Notation". Basically, JSON is Javascript, but limited to just filling an object with data. By executing a JSON object, you "load" the data in memory.
JavaScript is the bigger picture, with additional lines of code to manipulate the object or to do all kinds of other stuff.

A JSON example would be this:

{
    "glossary": {
        "title": "example glossary",
        "GlossDiv": {
            "title": "S",
            "GlossList": {
                "GlossEntry": {
                    "ID": "SGML",
                    "SortAs": "SGML",
                    "GlossTerm": "Standard Generalized Markup Language",
                    "Acronym": "SGML",
                    "Abbrev": "ISO 8879:1986",
                    "GlossDef": {
                        "para": "A meta-markup language, used to create markup languages such as DocBook.",
                        "GlossSeeAlso": ["GML", "XML"]
                    },
                    "GlossSee": "markup"
                }
            }
        }
    }
}

A JavaScript example would be this:

var Glossary = {
    "glossary": {
        "title": "example glossary",
        "GlossDiv": {
            "title": "S",
            "GlossList": {
                "GlossEntry": {
                    "ID": "SGML",
                    "SortAs": "SGML",
                    "GlossTerm": "Standard Generalized Markup Language",
                    "Acronym": "SGML",
                    "Abbrev": "ISO 8879:1986",
                    "GlossDef": {
                        "para": "A meta-markup language, used to create markup languages such as DocBook.",
                        "GlossSeeAlso": ["GML", "XML"]
                    },
                    "GlossSee": "markup"
                }
            }
        }
    }
}

Notice the var Glossary = in the JavaScript?

Comments

0

Well First of all a JavaScript is just like any other Object in object oriented programming.

And as RobG said JSON is effectively an object literal in Javascript Notation. But Not exactly. According to a Javascript book it says this is an object defined by using Object Notation:

var newObject = 
{     prop1 : true,     
showMessage : function (msg) {alert(msg)} 
}; 

According to JSON in JavaScript,

JSON is a subset of the object literal notation of JavaScript.

Also you might want to consider taking a look this link

Comments

0
var object = {
    name: "John",
    profession: "blogger"
};

alert(object.name);//John
alert(typeof(object));//Object
alert(object);//[object Object]


var json = JSON.stringify(object);

alert(json.name);//undefined
alert(typeof(json));//string
alert(json);//{"name":"John","profession":"blogger"}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.