Difference Between Json and Object Literal Notation

What is the difference between JSON and Object Literal Notation?

Lets clarify first what JSON actually is. JSON is a textual, language-independent data-exchange format, much like XML, CSV or YAML.

Data can be stored in many ways, but if it should be stored in a text file and be readable by a computer, it needs to follow some structure. JSON is one of the many formats that define such a structure.

Such formats are typically language-independent, meaning they can be processed by Java, Python, JavaScript, PHP, you name it.

In contrast, JavaScript is a programming language. Of course JavaScript also provides a way to define/describe data, but the syntax is very specific to JavaScript.

As a counter example, Python has the concept of tuples, their syntax is (x, y). JavaScript doesn't have something like this.


Lets look at the syntactical differences between JSON and JavaScript object literals.

JSON has the following syntactical constraints:

  • Object keys must be strings (i.e. a character sequence enclosed in double quotes ").
  • The values can be either:

    • a string
    • a number
    • an (JSON) object
    • an array
    • true
    • false
    • null
  • Duplicate keys ({"foo":"bar","foo":"baz"}) produce undefined, implementation-specific results; the JSON specification specifically does not define their semantics

In JavaScript, object literals can have

  • String literals, number literals or identifier names as keys (since ES6, keys can now also be computed, which introduces yet another syntax).
  • The values can be any valid JavaScript expression, including function definitions and undefined.
  • Duplicate keys produce defined, specified results (in loose mode, the latter definition replaces the former; in strict mode, it's an error).

Knowing that, just by looking at the syntax, your example is not JSON because of two reasons:

  1. Your keys are not strings (literals). They are identifier names.
  2. You cannot assign a function as a value to a "JSON object" (because JSON doesn't define any syntax for functions).

But most importantly, to repeat my explanation from the beginning: You are in a JavaScript context. You define a JavaScript object. If any, a "JSON object" can only be contained in a string:

 var obj = {foo: 42}; // creates a JavaScript object (this is *not* JSON)
var json = '{"foo": 452}'; // creates a string containing JSON

That is, if you're writing JavaScript source code, and not dealing with a string, you're not dealing with JSON. Maybe you received the data as JSON (e.g., via ajax or reading from a file), but once you or a library you're using has parsed it, it's not JSON anymore.


Only because object literals and JSON look similar, it does not mean that you can name them interchangeably. See also There's no such thing as a "JSON Object".

What are the differences between JSON and JavaScript object?

First you should know what JSON is:

  • It is language agnostic data-interchange format.

The syntax of JSON was inspired by the JavaScript Object Literal notation, but there are differences between them.

For example, in JSON all keys must be quoted, while in object literals this is not necessary:

// JSON:
{ "foo": "bar" }

// Object literal:
var o = { foo: "bar" };

The quotes are mandatory on JSON because in JavaScript (more exactly in ECMAScript 3rd. Edition), the usage of reserved words as property names is disallowed, for example:

var o = { if: "foo" }; // SyntaxError in ES3

While, using a string literal as a property name (quoting the property name) gives no problems:

var o = { "if": "foo" }; 

So for "compatibility" (and easy eval'ing maybe?) the quotes are mandatory.

The data types in JSON are also restricted to the following values:

  • string
  • number
  • object
  • array
  • A literal as:

    • true
    • false
    • null

The grammar of Strings changes. They have to be delimited by double quotes, while in JavaScript, you can use single or double quotes interchangeably.

// Invalid JSON:
{ "foo": 'bar' }

The accepted JSON grammar of Numbers also changes, in JavaScript you can use Hexadecimal Literals, for example 0xFF, or (the infamous) Octal Literals e.g. 010. In JSON you can use only Decimal Literals.

// Invalid JSON:
{ "foo": 0xFF }

There are some buggy implementations (Firefox 3.5+, IE8+, json2.js) where octal literals are wrongly allowed, e.g. JSON.parse('01') should produce a SyntaxError.

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

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

Javascript object Vs JSON


  1. Is the key/property name valid both with/without quotes ?

The only time you need to enclose a key in quotes when using Object Literal notation is where the key is a reserved word or contains a special character (if, :, - etc). It is worth noting that a key in JSON must be enclosed in double quotes.



  1. If I convert the above object to JSON using var jSonString = JSON.stringify(testObject);, what is the difference between the 2 (JS obj and JSON)?

JSON is a data interchange format. It's a standard which describes how ordered lists and unordered maps, strings, booleans and numbers can be represented in a string. Just like XML and YAML is a way to pass structured information between languages, JSON is the same. A JavaScript object on the other hand is a physical type. Just like a PHP array, a C++ class/ struct, a JavaScript object is a type internal to JavaScript.

Here's a story. Let's imagine you've purchased some furniture from a store, and you want it delivered. However the only one left in stock is the display model, but you agree to buy it.

In the shop, the chest-of-drawers you've purchased is a living object:

    var chestOfDrawers = {
color: "red",
numberOfDrawers: 4
}

However, you can't send a chest-of-drawers in the post, so you dismantle it (read, stringify it). It's now useless in terms of furniture. It is now JSON. Its in flat pack form.

    {"color":"red","numberOfDrawers":4}

When you receive it, you then rebuild the chest-of-drawers (read, parse it). Its now back in object form.

The reason behind JSON, XML and YAML is to enable data to be transferred between programming languages in a format both participating languages can understand; you can't give PHP or C++ your JavaScript object directly; because each language represents an object differently under-the-hood. However, because we've stringified the object into JSON notation; i.e. a standardised way to represent data, we can transmit the JSON representation of the object to another language (C++, PHP), they can recreate the JavaScript object we had into their own object based on the JSON representation of the object.

It is important to note that JSON cannot represent functions or dates. If you attempt to stringify an object with a function member, the function will be omitted from the JSON representation. A date will be converted to a string;

    JSON.stringify({
foo: new Date(),
blah: function () {
alert('hello');
}
}); // returns the string "{"foo":"2011-11-28T10:21:33.939Z"}"


  1. For parsing a JSON string, is the method below recommended? var javascriptObj = JSON.parse(jSonString);

Yes, but older browsers don't support JSON natively (IE <8). To support these, you should include json2.js.

If you're using jQuery, you can call jQuery.parseJSON(), which will use JSON.parse() under the hood if it's supported and will otherwise fallback to a custom implementation to parse the input.

What's the difference between Javascript Object and JSON object

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

Javascript: What is the difference between object literal notation and the object constructor?

A constructor gives an object a sense of identity. It's essentially a blueprint for how to create it which can be re-used. It is very similar to and often confused with a class in classical OOP.

If you frequently have a bunch of "car" objects and there are methods or properties which often go with all cars, you can create a Car constructor to help encapsulate it.

function Car(numPassengers) {
this.numPassengers = numPassengers;
}

Car.prototype = {
accelerate: function () {
// blah
},
brake: function () {
// blah
}
};

var jetta = new Car(4);
var bmwZ4 = new Car(2);

An object literal is a way to pass a just-in-time object whose structure and creation does not need to be re-used. To compare to classical OOP, similar to a Map in Java (except that javascript object literals can still have methods). A common use case is a function which takes a bunch of possible parameters, but each one is optional.

function someActionThatTakesOptionalParams(options) {
if (options.doAlert) {
alert(options.doAlert);
}
if (options.someOtherProperty) {
// do some work
}
}

someActionThatTakesOptionalParams({
doAlert: 'this will show up in an alert box',
someOtherProperty: 5,
hello: 'world'
});

It's also a convenient way to just model data that gets passed to something else with no methods attached. For example, you have an API that takes JSON:

$.ajax({
url: 'someApiEndpoint',
method: 'get',
params: {
x: 5,
y: 10
}
});

fetch inner json object using javascript / node js

I am not sure in which representation you would like get the data. I can assume - you would like to get array of the names

let obj= 
{
"h4354desdfqw":{
name:"Computer",
os:"Window",
},
"hjsado24334":{
name:"Software",
type:"Adobe",
},
"qwsak032142":{
name:"hardware",
type:"hardisk",
},
}

const result = Object.values(obj).map(i => i.name);

console.log(result)

Object.values(obj).map(i => console.log(i.name));

Difference between javascript object literal notation and adding to objects

The main reason that object literals don't evaluate the identifier to the left of the colon is so you're not force to quote all literal names (as you do in JSON).

Bracket notation forces you to quote property names, if you don't, it will be evaluated as a variable.

The reason toString() does get called in the second example is because bar has to be converted to a string to be used as a property name.

In your first example, you're just creating a literal object (that is the exactly the same as {"foo" : 'blah'}). So that is never using the variable foo

If you want to create an object using a variable name, you can't use literal object notation, you have to use [] which is what forces it to call toString()

Here's a function to create objects with variable names in one expression.

function obj(key, value /*, key, value, ... */) {
var obj = {};
for (var i = 0, ln = arguments.length ; i < ln; i+=2) {
obj[arguments[i]] = arguments[i+1];
}
return obj;
}

Clearer Example

The fact that your variable names and values are the same doesn't help understanding the problem. Let me suggest this code

var foo = new Obj('fooValue');
var bar = new Obj('barValue');

var map = {foo : 'blah'};
map[bar] = "blah2";

// You expect map to be {fooValue: 'blah', barValue: 'blah2'}
// But it's {foo: 'blah', barValue: 'blah2'}

To do what you need, use my obj function

// Almost as clear as literal notation ???
var map = obj(
foo, 'blah',
bar, 'blah2'
);
// map = {fooValue: 'blah', barValue: 'blah2'} Yay!!


Related Topics



Leave a reply



Submit