views:

81

answers:

3

Hi,

Can someone tell me what is the main difference between a Javascript object defined by using "Object Literal Notation" and JSON object?

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)}
};

Why it is not a JSON object in this case? Just because it is not defined by using quotation marks?

Thanks,

+6  A: 

Best is to read the documentation.


The main differences:

  • The keys must be strings (i.e. enclosed in double quotes ") in JSON.
  • The values can be either:
    • a string
    • a number
    • an (JSON) object
    • an array
    • true
    • false
    • null

So in your example, it is not JSON because of two reasons:

  1. Your keys are not strings.
  2. You cannot assign a function as a value to an JSON object.
Felix Kling
Also note that JSON is a *subset* of Object Literal Notation
Sean Kinsey
+3  A: 

JSON has a much more limited syntax including:

  • Key values must be quoted
  • Strings must be quoted with " and not '
  • You have a more limited range of values (e.g. no functions allowed)
David Dorward
A: 

As far as I understand the main difference is the flexibility.

JSON is a kind of wrapper on "JavaScript Object Notation" which forces users to obey more strict rules for defining the objects. And it does this by limiting the possible object declaration ways provided by JavaScript Object Notation feature.

As a result we have a simpler and more standardized objects which suits better on data-exchange between platforms.

So basically, the newObject in my example above is an object defined by using JavaScript Objeect Notation; but it is not a 'valid' JSON object because it does not follow the rules that JSON standards require.

This link is also quite helpful: http://msdn.microsoft.com/en-us/library/bb299886.aspx

burak ozdogan