Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between a JS object literal and a JSON string?

I have confusion about what exactly people mean by Object Literals, JSON, JavaScript Objects, to me they seem similar:

{foo: 'bar', bar : 'baz'}

AFAIK, above is object literal, json as well as javascript object, isn't it?

Does object literal and json mean the same thing ?

How do you guys differentiate which is what?

like image 429
Dev555 Avatar asked Jun 08 '12 15:06

Dev555


2 Answers

The variable jsonString contains a JSON string:

var jsonString = '{"foo": "bar", "bar" : "baz"}'

The variable javascriptObject contains a javascript object, initialized using an object literal:

var javascriptObject =  {foo: 'bar', bar : 'baz'}

You can convert a json string to a javascript object with JSON.parse, and back again with JSON.stringify.

like image 195
Eric Avatar answered Oct 13 '22 13:10

Eric


JSON is a just a data format, like XML. True JSON should have the keys surrounded by double quotes, like so:

{"foo":"bar"}

JavaScript Objects are part of the JavaScript language, and have associated things such as a prototype.

Object literals is creating a javascript object in place with brackets as opposed to using the new keyword, or Object.create().

//object literal
var foo = {};

//equivalent
var foo = new Object();
like image 28
Ryan O'Donnell Avatar answered Oct 13 '22 14:10

Ryan O'Donnell