Related
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 anObject = {
property1 : true,
showMessage : function (msg) { alert(msg) }
};
Why isn't it a JSON object in this case? Just because it is not defined by using quotation marks?
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:
Your keys are not strings (literals). They are identifier names.
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".
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)
There is really no such thing as a "JSON Object".
The JSON spec is a syntax for encoding data as a string. What people call a "JSON Object" ( in javascript ) is really just an ordinary javascript object that has (probably) been de-serialized from a valid JSON string, and can be easily re-serialized as a valid JSON string. This generally means that it contains only data ( and not functions ). It also means that there are no dates, because JSON does not have a date type ( probably the most painful thing about JSON ;)
Furthermore, (side-rant...) when people talk about a "JSON Object", they almost always mean data that has the "curly-braces" at the top-level. This corresponds nicely to a javascript object. However, the JSON spec does not require that there be a single "curly-braces" object at the top-level of a JSON string. It is perfectly valid JSON to have a list at the top-level, or even to have just a single value. So, while every "JSON Object" corresponds to valid JSON, not all valid JSON strings correspond to what we would call a "JSON Object"! ( because the string could represent a list or an atomic value )
According to JSON in JavaScript,
JSON is a subset of the object
literal notation of JavaScript.
In other words, valid JSON is also valid JavaScript object literal notation but not necessarily the other way around.
In addition to reading the documentation, as #Filix King suggested, I also suggest playing around with the JSONLint online JSON validator. That's how I learned that the keys of JSON objects must be strings.
🔫 JSON: The Fat-Free Alternative to XML
JSON has been widely adopted by people who found that it made it a lot easier to produce distributed applications and services. The official Internet media type for JSON is application/json RFC 4627. JSON filenames use the extension .json.
â–º JavaScript Object Notation (JSON) is a lightweight, text-based, language-independent data interchange format. JSON has been used to exchange data between applications written in any Programming language.
The JSON object is a single object that contains two functions, parse and stringify, that are used to parse and construct JSON texts.
JSON.stringify produces a String that conforms to the following JSON grammar.
JSON.parse accepts a String that conforms to the JSON grammar.
The parseJSON method will be included in the Fourth Edition of ECMAScript. In the meantime, a JavaScript implementation is available at json.org.
var objLiteral = {foo: 42}; // JavaScript Object
console.log('Object Literal : ', objLiteral ); // Object {foo: 42}foo: 42__proto__: Object
// This is a JSON String, like what you'd get back from an AJAX request.
var jsonString = '{"foo": 452}';
console.log('JOSN String : ', jsonString ); // {"foo": 452}
// This is how you deserialize that JSON String into an Object.
var serverResposnceObject = JSON.parse( jsonString );
console.log('Converting Ajax response to JavaScript Object : ', serverResposnceObject); // Object {foo: 42}foo: 42 __proto__: Object
// And this is how you serialize an Object into a JSON String.
var serverRequestJSON = JSON.stringify( objLiteral );
console.log('Reqesting server with JSON Data : ', serverRequestJSON); // '{"foo": 452}'
JSON is subset of JavaScript. Javascript was derived from the ECMAScript Programming Language Standard.
â–º ECMAScript
ECMAScript has grown to be one of the world's most widely used general purpose programming languages. It is best known as the language embedded in web browsers but has also been widely adopted for server and embedded applications. ECMAScript is based on several originating technologies, the most well-known being JavaScript (Netscape Communications)) and JScript (Microsoft Corporation).). Though before 1994, ECMA was known as "European Computer Manufacturers Association", after 1994, when the organization became global, the "trademark" "Ecma" was kept for historical reasons.
ECMAScript is the language, whereas JavaScript, JScript, and even ActionScript are called "Dialects".
Dialects have been derived from the same language. They are are quite similar to each other as they have been derived from the same language but they have undergone some changes.
A dialect is a variation in the language itself. It is derived from a single language.
SQL Language - Hibernate MySQL Dialect, Oracle Dialect,.. which have some changes or added functionality.
Information about the browser and computer of your users.
navigator.appName // "Netscape"
ECMAScript is the scripting language that forms the basis of JavaScript. JavaScript language resources.
ECMA-262 Links
Initial Edition, June 1997
PDF.
2nd Edition, August 1998
PDF.
3rd Edition, December 1999 PDF.
5th Edition, December 2009 PDF.
5.1 Edition, June 2011 HTML.
6th Edition, June 2015 HTML.
7áµ—Ê° Edition, June 2016 HTML.
8th edition, June 2017 HTML.
9th Edition, 2018 HTML.
NOTE « 4th edition of ECMAScript not published as the work was incomplete.
JSON defines a small set of formatting rules for the portable representation of structured data.
â–º Key values must be quoted, only Strings are allowed for keys. If you use other than String it will convert to String. But not recommended to use keys other than String's. Check an example like this - { 'key':'val' } over RFC 4627 - jsonformatter
var storage = {
0 : null,
1 : "Hello"
};
console.log( storage[1] ); // Hello
console.log( JSON.stringify( storage ) ); // {"0":null,"1":"Hello","2":"world!"}
var objLiteral = {'key1':'val1'};
var arr = [10, 20], arr2 = [ 'Yash', 'Sam' ];
var obj = { k: 'v' }, obj2 = { k2: 'v2' };
var fun = function keyFun() {} ;
objLiteral[ arr ] = 'ArrayVal'; objLiteral[ arr2 ] = 'OverridenArrayVal';
objLiteral[ obj ] = 'ObjectVal'; objLiteral[ obj2 ] = 'OverridenObjectVal';
objLiteral[ fun ] = 'FunctionVal';
console.log( objLiteral );
// Object {key1: "val1", 10,20: "ArrayVal", Yash,Sam: "OverridenArrayVal", [object Object]: "OverridenObjectVal", function keyFun() {}: "FunctionVal"}
console.log( JSON.stringify( objLiteral ) );
// {"key1":"val1","10,20":"ArrayVal","Yash,Sam":"OverridenArrayVal","[object Object]":"OverridenObjectVal","function keyFun() {}":"FunctionVal"}
console.log( JSON.parse( JSON.stringify( objLiteral ) ) );
// Object {key1: "val1", 10,20: "ArrayVal", Yash,Sam: "OverridenArrayVal", [object Object]: "OverridenObjectVal", function keyFun() {}: "FunctionVal"}
console.log('Accessing Array Val : ', objLiteral[ [10,20] ] );
console.log('Accessing Object Val : ', objLiteral[ '[object Object]' ] );
console.log('Accessing Function Val : ', objLiteral[ 'function keyFun() {}' ] );
â–º JSON Strings must be quoted with " and not '. A string is very much like a C or Java string. Strings should be wrapped in double quotes.
Literals are fixed values, not variables, that you literally provide in your script.
A string is a sequence of zero or more characters wrapped in quotes with backslash escapement, the same notation used in most programming languages.
🔫 - Special Symbols are allowed in String but not recomended to use.
" - Special characters can be escaped. But not recomended to escape (') Single Quotes.
In Strict mode it will throw and Error - SyntaxError: Unexpected token ' in JSON
Check with this code { "Hai\" \n Team 🔫":5, "Bye \'": 7 } over online JSON Edtions. Modes notStrict, Strinct.
var jsonString = "{'foo': 452}"; // {'foo': 452}
var jsonStr = '{"foo": 452}'; // {"foo": 452}
JSON.parse( jsonString ); // Unexpected token ' in JSON at position 1(…)
JSON.parse( jsonStr ); // Object {foo: 452}
objLiteral['key'] = 'val'; // Object {foo: 42, key: "val"}
objLiteral.key2 = 'val';
// objLiteral.key\n3 - SyntaxError: Invalid or unexpected token
objLiteral['key\n3'] = 'val'; // Object {"foo": "42", key: "val", key2: "val", "key↵3": "val"}
JSON.stringify( objLiteral ); // {"foo":"42","key":"val","key2":"val","key\n3":"val"}
Object Property accessors provide access to an object's properties by using the dot notation or the bracket notation.
â–º You have a more limited range of values (e.g. no functions allowed). A value can be a string in double quotes, number, boolean, null, object, or array. These structures can be nested.
var objLiteral = {};
objLiteral.funKey = function sayHello() {
console.log('Object Key with function as value - Its outcome message.');
};
objLiteral['Key'] = 'Val';
console.log('Object Literal Fun : ', objLiteral );
// Object Literal Fun : Object {Key: "Val"}Key: "Val"funKey: sayHello()__proto__: Object
console.log( JSON.stringify( objLiteral ) ); // {"Key":"Val"}
â–º JavaScript is the most popular implementation of the ECMAScript Standard.
The core features of Javascript are based on the ECMAScript standard, but Javascript also has other additional features that are not in the ECMA specifications/standard. Every browser has a JavaScript interpreter.
JavaScript is a dynamically typed language. That means you don't have to specify the data type of a variable when you declare it, and data types are converted automatically as needed during script execution.
Literals :
'37' - 7 // 30
'37' + 7 // "377"
+'37' + 7 // 44
+'37' // 37
'37' // "37"
parseInt('37'); // 37
parseInt('3.7'); // 3
parseFloat(3.7); // 3.7
// An alternative method of retrieving a number from a string is with the + (unary plus) operator:
+'3.7' // 3.7
Object literals RFC 7159
An object structure is represented as a pair of curly brackets surrounding zero or more name/value pairs (or members). A name is a
string. A single colon comes after each name, separating the name from the value. A single comma separates a value from a following
name. The names within an object SHOULD be unique.
ECMAScript supports prototype-based inheritance. Every constructor has an associated prototype, and every object created by that constructor has an implicit reference to the prototype (called the object’s
prototype) associated with its constructor. Furthermore, a prototype may have a non-null implicit reference to its prototype, and so on; this is called the prototype chain.
In a class-based object-oriented language, in general, state is carried by instances, methods are carried by classes, and inheritance is only of structure and behavior. In ECMAScript, the state and methods are carried by objects, and structure, behavior, and state are all inherited.
A prototype is an object used to implement structure, state, and behavior inheritance in ECMAScript. When a constructor creates an object, that object implicitly references the constructor’s associated prototype for the purpose of resolving property references. The constructor’s associated prototype can
be referenced by the program expression constructor.prototype, and properties added to an object’s prototype are shared, through inheritance, by all objects sharing the prototype.
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
For the ones who still think that RFC are more important than blogs and opinion based misconceptions, let's try to answer clarifying some points.
I'm not going to repeat all the correct differences already mentioned in previous answers, here I'm just trying adding value summarizing some crucial part rfc7159
Extracts from https://www.rfc-editor.org/rfc/rfc7159
JavaScript Object Notation (JSON) is a text format for the
serialization of structured data. It is derived from the object
literals of JavaScript, as defined in the ECMAScript Programming
Language Standard, Third Edition [ECMA-262].
JSON can represent four primitive types (strings, numbers, booleans,
and null) and two structured types (objects and arrays).
An object is an unordered collection of zero or more name/value
pairs, where a name is a string and a value is a string, number,
boolean, null, object, or array.
begin-object = ws %x7B ws ; { left curly bracket
end-object = ws %x7D ws ; } right curly bracket
A JSON value MUST be an object, array, number, or string, or one of
the following three literal names: false null true
An object structure is represented as a pair of curly brackets
The names within an object SHOULD be unique.
object = begin-object [ member *( value-separator member ) ]
end-object
An object whose names are all unique is interoperable in the sense
that all software implementations receiving that object will agree on
the name-value mappings. When the names within an object are not
unique, the behavior of software that receives such an object is
unpredictable.
Examples (from page 12 of RFC)
This is a JSON object:
{
"Image": {
"Width": 800,
"Height": 600,
"Title": "View from 15th Floor",
"Thumbnail": {
"Url": "http://www.example.com/image/481989943",
"Height": 125,
"Width": 100
},
"Animated" : false,
"IDs": [116, 943, 234, 38793]
}
}
Its Image member is an object whose Thumbnail member is an object and
whose IDs member is an array of numbers.
There is really no such thing as a "JSON Object".
Really?
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 }
Here is one surprising difference: you can not use undefined in json and all object fields with undefined values will disappear after JSON.stringify
let object = { "a": undefined } ;
let badJSON= '{ "a": undefined }';
console.log('valid JS object :', object );
console.log('JSON from object:', JSON.stringify(object) );
console.log('invalid json :', JSON.parse(badJSON) );
🙈🙉🙊
Javascript Object Literal vs JSON:
Object literal syntax is a very convenient way to create javascript objects
The JSON language, which stands for 'Javascript object notation', has its syntax derived from javascript object literal syntax. It is used as a programming language independent textual data transfer format.
Example:
JS object notation, used in JS to create objects in the code conveniently:
const JS_Object = {
1: 2, // the key here is the number 1, the value is the number 2
a: 'b', // the key is the string a, the value is the string b
func: function () { console.log('hi') }
// the key is func, the value is the function
}
Example of JSON:
{"widget": {
"debug": "on",
"window": {
"title": "Sample Konfabulator Widget",
"name": "main_window",
"width": 500,
"height": 500
},
"image": {
"src": "Images/Sun.png",
"name": "sun1",
"hOffset": 250,
"vOffset": 250,
"alignment": "center"
},
"text": {
"data": "Click Here",
"size": 36,
"style": "bold",
"name": "text1",
"hOffset": 250,
"vOffset": 100,
"alignment": "center",
"onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
}
}}
Main differences:
All object keys in JSON must be strings. In Javascript object keys can be strings or numbers
All strings in JSON must be quoted in "double quotes". Whereas in Javascript both single quotes and double quotes are allowed. Even with no quotes in the Javascript object notation the object keys are implicitly casted to strings.
In JSON a function cannot be defined as a value of an object (since this is Javascript specific). In Javascript this is completely legal.
Javascript build in JSON object:
JSON objects can be easily converted to Javascript and vice versa using the built in JSON object which Javascript offers in its runtime. For example:
const Object = {
property1: true,
property2: false,
}; // creating object with JS object literal syntax
const JSON_object = JSON.stringify(Object); // stringify JS object to a JSON string
console.log(JSON_object); // note that the (string) keys are in double quotes
const JS_object = JSON.parse(JSON_object); // parse JSON string to JS object
console.log(JS_object.property1, JS_object.property2);
// accessing keys of the newly created object
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 anObject = {
property1 : true,
showMessage : function (msg) { alert(msg) }
};
Why isn't it a JSON object in this case? Just because it is not defined by using quotation marks?
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:
Your keys are not strings (literals). They are identifier names.
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".
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)
There is really no such thing as a "JSON Object".
The JSON spec is a syntax for encoding data as a string. What people call a "JSON Object" ( in javascript ) is really just an ordinary javascript object that has (probably) been de-serialized from a valid JSON string, and can be easily re-serialized as a valid JSON string. This generally means that it contains only data ( and not functions ). It also means that there are no dates, because JSON does not have a date type ( probably the most painful thing about JSON ;)
Furthermore, (side-rant...) when people talk about a "JSON Object", they almost always mean data that has the "curly-braces" at the top-level. This corresponds nicely to a javascript object. However, the JSON spec does not require that there be a single "curly-braces" object at the top-level of a JSON string. It is perfectly valid JSON to have a list at the top-level, or even to have just a single value. So, while every "JSON Object" corresponds to valid JSON, not all valid JSON strings correspond to what we would call a "JSON Object"! ( because the string could represent a list or an atomic value )
According to JSON in JavaScript,
JSON is a subset of the object
literal notation of JavaScript.
In other words, valid JSON is also valid JavaScript object literal notation but not necessarily the other way around.
In addition to reading the documentation, as #Filix King suggested, I also suggest playing around with the JSONLint online JSON validator. That's how I learned that the keys of JSON objects must be strings.
🔫 JSON: The Fat-Free Alternative to XML
JSON has been widely adopted by people who found that it made it a lot easier to produce distributed applications and services. The official Internet media type for JSON is application/json RFC 4627. JSON filenames use the extension .json.
â–º JavaScript Object Notation (JSON) is a lightweight, text-based, language-independent data interchange format. JSON has been used to exchange data between applications written in any Programming language.
The JSON object is a single object that contains two functions, parse and stringify, that are used to parse and construct JSON texts.
JSON.stringify produces a String that conforms to the following JSON grammar.
JSON.parse accepts a String that conforms to the JSON grammar.
The parseJSON method will be included in the Fourth Edition of ECMAScript. In the meantime, a JavaScript implementation is available at json.org.
var objLiteral = {foo: 42}; // JavaScript Object
console.log('Object Literal : ', objLiteral ); // Object {foo: 42}foo: 42__proto__: Object
// This is a JSON String, like what you'd get back from an AJAX request.
var jsonString = '{"foo": 452}';
console.log('JOSN String : ', jsonString ); // {"foo": 452}
// This is how you deserialize that JSON String into an Object.
var serverResposnceObject = JSON.parse( jsonString );
console.log('Converting Ajax response to JavaScript Object : ', serverResposnceObject); // Object {foo: 42}foo: 42 __proto__: Object
// And this is how you serialize an Object into a JSON String.
var serverRequestJSON = JSON.stringify( objLiteral );
console.log('Reqesting server with JSON Data : ', serverRequestJSON); // '{"foo": 452}'
JSON is subset of JavaScript. Javascript was derived from the ECMAScript Programming Language Standard.
â–º ECMAScript
ECMAScript has grown to be one of the world's most widely used general purpose programming languages. It is best known as the language embedded in web browsers but has also been widely adopted for server and embedded applications. ECMAScript is based on several originating technologies, the most well-known being JavaScript (Netscape Communications)) and JScript (Microsoft Corporation).). Though before 1994, ECMA was known as "European Computer Manufacturers Association", after 1994, when the organization became global, the "trademark" "Ecma" was kept for historical reasons.
ECMAScript is the language, whereas JavaScript, JScript, and even ActionScript are called "Dialects".
Dialects have been derived from the same language. They are are quite similar to each other as they have been derived from the same language but they have undergone some changes.
A dialect is a variation in the language itself. It is derived from a single language.
SQL Language - Hibernate MySQL Dialect, Oracle Dialect,.. which have some changes or added functionality.
Information about the browser and computer of your users.
navigator.appName // "Netscape"
ECMAScript is the scripting language that forms the basis of JavaScript. JavaScript language resources.
ECMA-262 Links
Initial Edition, June 1997
PDF.
2nd Edition, August 1998
PDF.
3rd Edition, December 1999 PDF.
5th Edition, December 2009 PDF.
5.1 Edition, June 2011 HTML.
6th Edition, June 2015 HTML.
7áµ—Ê° Edition, June 2016 HTML.
8th edition, June 2017 HTML.
9th Edition, 2018 HTML.
NOTE « 4th edition of ECMAScript not published as the work was incomplete.
JSON defines a small set of formatting rules for the portable representation of structured data.
â–º Key values must be quoted, only Strings are allowed for keys. If you use other than String it will convert to String. But not recommended to use keys other than String's. Check an example like this - { 'key':'val' } over RFC 4627 - jsonformatter
var storage = {
0 : null,
1 : "Hello"
};
console.log( storage[1] ); // Hello
console.log( JSON.stringify( storage ) ); // {"0":null,"1":"Hello","2":"world!"}
var objLiteral = {'key1':'val1'};
var arr = [10, 20], arr2 = [ 'Yash', 'Sam' ];
var obj = { k: 'v' }, obj2 = { k2: 'v2' };
var fun = function keyFun() {} ;
objLiteral[ arr ] = 'ArrayVal'; objLiteral[ arr2 ] = 'OverridenArrayVal';
objLiteral[ obj ] = 'ObjectVal'; objLiteral[ obj2 ] = 'OverridenObjectVal';
objLiteral[ fun ] = 'FunctionVal';
console.log( objLiteral );
// Object {key1: "val1", 10,20: "ArrayVal", Yash,Sam: "OverridenArrayVal", [object Object]: "OverridenObjectVal", function keyFun() {}: "FunctionVal"}
console.log( JSON.stringify( objLiteral ) );
// {"key1":"val1","10,20":"ArrayVal","Yash,Sam":"OverridenArrayVal","[object Object]":"OverridenObjectVal","function keyFun() {}":"FunctionVal"}
console.log( JSON.parse( JSON.stringify( objLiteral ) ) );
// Object {key1: "val1", 10,20: "ArrayVal", Yash,Sam: "OverridenArrayVal", [object Object]: "OverridenObjectVal", function keyFun() {}: "FunctionVal"}
console.log('Accessing Array Val : ', objLiteral[ [10,20] ] );
console.log('Accessing Object Val : ', objLiteral[ '[object Object]' ] );
console.log('Accessing Function Val : ', objLiteral[ 'function keyFun() {}' ] );
â–º JSON Strings must be quoted with " and not '. A string is very much like a C or Java string. Strings should be wrapped in double quotes.
Literals are fixed values, not variables, that you literally provide in your script.
A string is a sequence of zero or more characters wrapped in quotes with backslash escapement, the same notation used in most programming languages.
🔫 - Special Symbols are allowed in String but not recomended to use.
" - Special characters can be escaped. But not recomended to escape (') Single Quotes.
In Strict mode it will throw and Error - SyntaxError: Unexpected token ' in JSON
Check with this code { "Hai\" \n Team 🔫":5, "Bye \'": 7 } over online JSON Edtions. Modes notStrict, Strinct.
var jsonString = "{'foo': 452}"; // {'foo': 452}
var jsonStr = '{"foo": 452}'; // {"foo": 452}
JSON.parse( jsonString ); // Unexpected token ' in JSON at position 1(…)
JSON.parse( jsonStr ); // Object {foo: 452}
objLiteral['key'] = 'val'; // Object {foo: 42, key: "val"}
objLiteral.key2 = 'val';
// objLiteral.key\n3 - SyntaxError: Invalid or unexpected token
objLiteral['key\n3'] = 'val'; // Object {"foo": "42", key: "val", key2: "val", "key↵3": "val"}
JSON.stringify( objLiteral ); // {"foo":"42","key":"val","key2":"val","key\n3":"val"}
Object Property accessors provide access to an object's properties by using the dot notation or the bracket notation.
â–º You have a more limited range of values (e.g. no functions allowed). A value can be a string in double quotes, number, boolean, null, object, or array. These structures can be nested.
var objLiteral = {};
objLiteral.funKey = function sayHello() {
console.log('Object Key with function as value - Its outcome message.');
};
objLiteral['Key'] = 'Val';
console.log('Object Literal Fun : ', objLiteral );
// Object Literal Fun : Object {Key: "Val"}Key: "Val"funKey: sayHello()__proto__: Object
console.log( JSON.stringify( objLiteral ) ); // {"Key":"Val"}
â–º JavaScript is the most popular implementation of the ECMAScript Standard.
The core features of Javascript are based on the ECMAScript standard, but Javascript also has other additional features that are not in the ECMA specifications/standard. Every browser has a JavaScript interpreter.
JavaScript is a dynamically typed language. That means you don't have to specify the data type of a variable when you declare it, and data types are converted automatically as needed during script execution.
Literals :
'37' - 7 // 30
'37' + 7 // "377"
+'37' + 7 // 44
+'37' // 37
'37' // "37"
parseInt('37'); // 37
parseInt('3.7'); // 3
parseFloat(3.7); // 3.7
// An alternative method of retrieving a number from a string is with the + (unary plus) operator:
+'3.7' // 3.7
Object literals RFC 7159
An object structure is represented as a pair of curly brackets surrounding zero or more name/value pairs (or members). A name is a
string. A single colon comes after each name, separating the name from the value. A single comma separates a value from a following
name. The names within an object SHOULD be unique.
ECMAScript supports prototype-based inheritance. Every constructor has an associated prototype, and every object created by that constructor has an implicit reference to the prototype (called the object’s
prototype) associated with its constructor. Furthermore, a prototype may have a non-null implicit reference to its prototype, and so on; this is called the prototype chain.
In a class-based object-oriented language, in general, state is carried by instances, methods are carried by classes, and inheritance is only of structure and behavior. In ECMAScript, the state and methods are carried by objects, and structure, behavior, and state are all inherited.
A prototype is an object used to implement structure, state, and behavior inheritance in ECMAScript. When a constructor creates an object, that object implicitly references the constructor’s associated prototype for the purpose of resolving property references. The constructor’s associated prototype can
be referenced by the program expression constructor.prototype, and properties added to an object’s prototype are shared, through inheritance, by all objects sharing the prototype.
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
For the ones who still think that RFC are more important than blogs and opinion based misconceptions, let's try to answer clarifying some points.
I'm not going to repeat all the correct differences already mentioned in previous answers, here I'm just trying adding value summarizing some crucial part rfc7159
Extracts from https://www.rfc-editor.org/rfc/rfc7159
JavaScript Object Notation (JSON) is a text format for the
serialization of structured data. It is derived from the object
literals of JavaScript, as defined in the ECMAScript Programming
Language Standard, Third Edition [ECMA-262].
JSON can represent four primitive types (strings, numbers, booleans,
and null) and two structured types (objects and arrays).
An object is an unordered collection of zero or more name/value
pairs, where a name is a string and a value is a string, number,
boolean, null, object, or array.
begin-object = ws %x7B ws ; { left curly bracket
end-object = ws %x7D ws ; } right curly bracket
A JSON value MUST be an object, array, number, or string, or one of
the following three literal names: false null true
An object structure is represented as a pair of curly brackets
The names within an object SHOULD be unique.
object = begin-object [ member *( value-separator member ) ]
end-object
An object whose names are all unique is interoperable in the sense
that all software implementations receiving that object will agree on
the name-value mappings. When the names within an object are not
unique, the behavior of software that receives such an object is
unpredictable.
Examples (from page 12 of RFC)
This is a JSON object:
{
"Image": {
"Width": 800,
"Height": 600,
"Title": "View from 15th Floor",
"Thumbnail": {
"Url": "http://www.example.com/image/481989943",
"Height": 125,
"Width": 100
},
"Animated" : false,
"IDs": [116, 943, 234, 38793]
}
}
Its Image member is an object whose Thumbnail member is an object and
whose IDs member is an array of numbers.
There is really no such thing as a "JSON Object".
Really?
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 }
Here is one surprising difference: you can not use undefined in json and all object fields with undefined values will disappear after JSON.stringify
let object = { "a": undefined } ;
let badJSON= '{ "a": undefined }';
console.log('valid JS object :', object );
console.log('JSON from object:', JSON.stringify(object) );
console.log('invalid json :', JSON.parse(badJSON) );
🙈🙉🙊
Javascript Object Literal vs JSON:
Object literal syntax is a very convenient way to create javascript objects
The JSON language, which stands for 'Javascript object notation', has its syntax derived from javascript object literal syntax. It is used as a programming language independent textual data transfer format.
Example:
JS object notation, used in JS to create objects in the code conveniently:
const JS_Object = {
1: 2, // the key here is the number 1, the value is the number 2
a: 'b', // the key is the string a, the value is the string b
func: function () { console.log('hi') }
// the key is func, the value is the function
}
Example of JSON:
{"widget": {
"debug": "on",
"window": {
"title": "Sample Konfabulator Widget",
"name": "main_window",
"width": 500,
"height": 500
},
"image": {
"src": "Images/Sun.png",
"name": "sun1",
"hOffset": 250,
"vOffset": 250,
"alignment": "center"
},
"text": {
"data": "Click Here",
"size": 36,
"style": "bold",
"name": "text1",
"hOffset": 250,
"vOffset": 100,
"alignment": "center",
"onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
}
}}
Main differences:
All object keys in JSON must be strings. In Javascript object keys can be strings or numbers
All strings in JSON must be quoted in "double quotes". Whereas in Javascript both single quotes and double quotes are allowed. Even with no quotes in the Javascript object notation the object keys are implicitly casted to strings.
In JSON a function cannot be defined as a value of an object (since this is Javascript specific). In Javascript this is completely legal.
Javascript build in JSON object:
JSON objects can be easily converted to Javascript and vice versa using the built in JSON object which Javascript offers in its runtime. For example:
const Object = {
property1: true,
property2: false,
}; // creating object with JS object literal syntax
const JSON_object = JSON.stringify(Object); // stringify JS object to a JSON string
console.log(JSON_object); // note that the (string) keys are in double quotes
const JS_object = JSON.parse(JSON_object); // parse JSON string to JS object
console.log(JS_object.property1, JS_object.property2);
// accessing keys of the newly created object
Wikipedia says that JSON is designed as non-strict subset of JavaScript, that is addition allows usage of some Unicode characters. Quoting current version as of 2015-11-05:
Though JSON is commonly perceived as being a subset of JavaScript and ECMAScript, it allows some unescaped characters in strings that are illegal in JavaScript and ECMAScript strings.
But.. if I paste any of examples from Wikipedia page in ESLint, it fails with error.
For example I paste this:
{
"id": 1,
"name": "Foo"
}
Into http://eslint.org/demo/ and get:
2:8 - Parsing error: Unexpected token : (undefined)
Looks like colon is illegal in JavaScript for some reason and it is not about unescaped characters in strings.
Why people still call JSON a JavaScript subset?
JSON is a subset of JavaScript object notation. You can't just declare an object out of nowhere.
The JavaScript usage of that object would be to assign it to a variable:
var o = {
"id": 1,
"name": "Foo"
};
or pass it to a function:
console.dir( {"id": 1, "name": "Foo" } );
etc.
You're running into a somewhat common problem: a loose object literal is interpreted as a block, rather than an object.
If you add var foo = to the beginning, it's perfectly valid:
var foo = {
"id": 1,
"name": "Foo"
}
Without the var foo to declare and initialize a variable, the parser sees a block (like if (true) { ... }) and string literal ("id"). The colon is not legal after a loose string literal, because that isn't real JS anywhere:
"id": foo(); // doesn't make sense
This is more often seen with unquoted properties in the object literal, which the parser interprets as named labels (the rarely-used foo: syntax for use with goto). The construct
{
id: 1,
name: "Foo"
}
looks like a block with a label id (which points to the expression 1), the comma operator, and another label. Again, that doesn't make much sense, but the first section is at least a legal parse.
Because you've followed the JSON spec rather than JS object literals and quoted your property names, it's picking them up as string literals and can't figure out what to do from there.
Amusingly, if you were to use:
{
"id".toString(),
"name".substr(1)
}
then ESlint doesn't complain. It's weird and not very useful, but a completely legal language construct.
The issue is that the parser is not able to figure out that it is object context yet. You can wrap it in ():
({
"id": 1,
"name": "Foo"
})
it will do what you expect.
JSON is a subset because it is meant for data only. JavaScript allows defining functions and executing statements. JSON only allows defining data. That is why it is a subset.
The error you received trying to validate the JSON as a JavaScript statement, is that your data is not a statement. Convert it to a statement to not see the error on eslint:
var foo = {
"id": 1,
"name": "Foo"
};
I want to understand the basic differences clearly between Javascript object and JSON string.
Let's say I create the following JS variable:
var testObject = {one: 1,"two":2,"three":3};
Q1. Is the key/property name valid both with/without quotes? (e.g. "one" : 1)
If yes, what is the difference?
Q2: If I convert the above object using JSON.stringify(testObject), what’s the difference between the original JS object and the JSON?
I feel they are almost the same. Please elaborate on this.
Q3: For parsing a JSON string, is the method below recommended?
var javascriptObj = JSON.parse(jSonString);
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.
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"}"
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.
Q1: When defining object literals in javascript, the keys may include quotes or not. There is no difference except that quotes allow you to specify certain keys that would cause the interpreter to fail to parse if you tried them bare. For example, if you wanted a key that was just an exclamation point, you would need quotes:
a = { "!": 1234 } // Valid
a = { !: 1234 } // Syntax error
In most cases though, you can omit the quotes around keys on object literals.
Q2: JSON is literally a string representation. It is just a string. So, consider this:
var testObject = { hello: "world" }
var jSonString = JSON.stringify(testObject);
Since testObject is a real object, you can call properties on it and do anything else you can do with objects:
testObject.hello => "world"
On the other hand, jsonString is just a string:
jsonString.hello => undefined
Note one other difference: In JSON, all keys must be quoted. That contrasts with object literals, where the quotes can usually be omitted as per my explanation in Q1.
Q3. You can parse a JSON string by using JSON.parse, and this is generally the best way to do it (if the browser or a framework provides it). You can also just use eval since JSON is valid javascript code, but the former method is recommended for a number of reasons (eval has a lot of nasty problems associated with it).
Problems solved by JSON
Let's say you want to exchange regular JavaScript objects between two computers, and you set two rules:
The transmitted data must be a regular string.
Only attributes can be exchanged, methods are not transmitted.
Now you create two objects on the first host:
var obj1 = { one: 1,"two":2,"three":3 }; // your example
var obj2 = { one: obj1.one, two: 2, three: obj1.one + obj1.two };
How can you convert those objects into strings for transmission to the second host?
For the first object, you could send this string obtained form the literal definition '{ one: 1,"two":2,"three":3 }', but actually you can't read the literal in the script portion of the document (at least not easily). So obj1 and obj2 must actually be processed the same way.
You need to enumerate all attributes and their value, and build a string similar to the object literal.
JSON has been created as a solution to the needs just discussed: It is a set of rules to create a string equivalent to an object by listing all attributes and values (methods are ignored).
JSON normalizes the use of double-quotes for attribute names and values.
Remember that JSON is a set of rules only (a standard).
How many JSON objects are created?
Only one, it is automatically created by the JS engine.
Modern JavaScript engines found in browsers have a native object, also named JSON. This JSON object is able to:
Decode a string built using JSON standard, using JSON.parse(string). The result is a regular JS object with attributes and values found in the JSON string.
Encode attributes / values of a regular JS object using JSON.stringify(). The result is a string compliant with the JSON set of rules.
The (single) JSON object is similar to a codec, it's function is to encode and decode.
Note that:
JSON.parse() doesn't create a JSON object, it creates a regular JS object, there is no difference between an object created using an object literal and an object created by JSON.parse() from a JSON-compliant string.
There is only one JSON object, which is used for all conversions.
Going back to the questions:
Q1: The use of single of double quotes is allowed for object literals. Note that the quotes are used optionally for attributes names, and are mandatory for string values. The object literal itself is not surrounded by quotes.
Q2: Objects created from literals and using JSON.parse() are strictly the same. These two objects are equivalent after creation:
var obj1 = { one: 1, "two": 2, "three": 3 };
var obj2 = JSON.parse('{ "one": "1", "two": "2", "three": "3" }');
Q3: On modern browsers JSON.parse() is used to create a JS object from a JSON-compliant string. (jQuery has also an equivalent method that can be used for all browsers).
Q1 - in JS you only need to use quotes if the key is a reserved word or if it would otherwise be an illegal token. In JSON you MUST always use double quotes on key names.
Q2 - the jsonString is a serialised version of the input object ...
Q3 - which may be deserialised to an identical looking object using JSON.parse()
Question already has good answers posted, I am adding a small example below, which will make it more easy to understand the explanations given in previous answers.
Copy paste below snippet to your IDE for better understanding and comment the
line containing invalid_javascript_object_no_quotes object declaration to avoid compile time error.
// Valid JSON strings(Observe quotes)
valid_json = '{"key":"value"}'
valid_json_2 = '{"key 1":"value 1"}' // Observe the space(special character) in key - still valid
//Valid Javascript object
valid_javascript_object_no_quotes = {
key: "value" //No special character in key, hence it is valid without quotes for key
}
//Valid Javascript object
valid_javascript_object_quotes = {
key:"value", //No special character in key, hence it is valid without quotes for key
"key 1": "value 1" // Space (special character) present in key, therefore key must be contained in double quotes - Valid
}
console.log(typeof valid_json) // string
console.log(typeof valid_javascript_object_no_quotes) // object
console.log(typeof valid_javascript_object_quotes) // object
//Invalid Javascript object
invalid_javascript_object_no_quotes = {
key 1: "value"//Space (special character) present in key, since key is not enclosed with double quotes "Invalid Javascript Object"
}
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 anObject = {
property1 : true,
showMessage : function (msg) { alert(msg) }
};
Why isn't it a JSON object in this case? Just because it is not defined by using quotation marks?
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:
Your keys are not strings (literals). They are identifier names.
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".
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)
There is really no such thing as a "JSON Object".
The JSON spec is a syntax for encoding data as a string. What people call a "JSON Object" ( in javascript ) is really just an ordinary javascript object that has (probably) been de-serialized from a valid JSON string, and can be easily re-serialized as a valid JSON string. This generally means that it contains only data ( and not functions ). It also means that there are no dates, because JSON does not have a date type ( probably the most painful thing about JSON ;)
Furthermore, (side-rant...) when people talk about a "JSON Object", they almost always mean data that has the "curly-braces" at the top-level. This corresponds nicely to a javascript object. However, the JSON spec does not require that there be a single "curly-braces" object at the top-level of a JSON string. It is perfectly valid JSON to have a list at the top-level, or even to have just a single value. So, while every "JSON Object" corresponds to valid JSON, not all valid JSON strings correspond to what we would call a "JSON Object"! ( because the string could represent a list or an atomic value )
According to JSON in JavaScript,
JSON is a subset of the object
literal notation of JavaScript.
In other words, valid JSON is also valid JavaScript object literal notation but not necessarily the other way around.
In addition to reading the documentation, as #Filix King suggested, I also suggest playing around with the JSONLint online JSON validator. That's how I learned that the keys of JSON objects must be strings.
🔫 JSON: The Fat-Free Alternative to XML
JSON has been widely adopted by people who found that it made it a lot easier to produce distributed applications and services. The official Internet media type for JSON is application/json RFC 4627. JSON filenames use the extension .json.
â–º JavaScript Object Notation (JSON) is a lightweight, text-based, language-independent data interchange format. JSON has been used to exchange data between applications written in any Programming language.
The JSON object is a single object that contains two functions, parse and stringify, that are used to parse and construct JSON texts.
JSON.stringify produces a String that conforms to the following JSON grammar.
JSON.parse accepts a String that conforms to the JSON grammar.
The parseJSON method will be included in the Fourth Edition of ECMAScript. In the meantime, a JavaScript implementation is available at json.org.
var objLiteral = {foo: 42}; // JavaScript Object
console.log('Object Literal : ', objLiteral ); // Object {foo: 42}foo: 42__proto__: Object
// This is a JSON String, like what you'd get back from an AJAX request.
var jsonString = '{"foo": 452}';
console.log('JOSN String : ', jsonString ); // {"foo": 452}
// This is how you deserialize that JSON String into an Object.
var serverResposnceObject = JSON.parse( jsonString );
console.log('Converting Ajax response to JavaScript Object : ', serverResposnceObject); // Object {foo: 42}foo: 42 __proto__: Object
// And this is how you serialize an Object into a JSON String.
var serverRequestJSON = JSON.stringify( objLiteral );
console.log('Reqesting server with JSON Data : ', serverRequestJSON); // '{"foo": 452}'
JSON is subset of JavaScript. Javascript was derived from the ECMAScript Programming Language Standard.
â–º ECMAScript
ECMAScript has grown to be one of the world's most widely used general purpose programming languages. It is best known as the language embedded in web browsers but has also been widely adopted for server and embedded applications. ECMAScript is based on several originating technologies, the most well-known being JavaScript (Netscape Communications)) and JScript (Microsoft Corporation).). Though before 1994, ECMA was known as "European Computer Manufacturers Association", after 1994, when the organization became global, the "trademark" "Ecma" was kept for historical reasons.
ECMAScript is the language, whereas JavaScript, JScript, and even ActionScript are called "Dialects".
Dialects have been derived from the same language. They are are quite similar to each other as they have been derived from the same language but they have undergone some changes.
A dialect is a variation in the language itself. It is derived from a single language.
SQL Language - Hibernate MySQL Dialect, Oracle Dialect,.. which have some changes or added functionality.
Information about the browser and computer of your users.
navigator.appName // "Netscape"
ECMAScript is the scripting language that forms the basis of JavaScript. JavaScript language resources.
ECMA-262 Links
Initial Edition, June 1997
PDF.
2nd Edition, August 1998
PDF.
3rd Edition, December 1999 PDF.
5th Edition, December 2009 PDF.
5.1 Edition, June 2011 HTML.
6th Edition, June 2015 HTML.
7áµ—Ê° Edition, June 2016 HTML.
8th edition, June 2017 HTML.
9th Edition, 2018 HTML.
NOTE « 4th edition of ECMAScript not published as the work was incomplete.
JSON defines a small set of formatting rules for the portable representation of structured data.
â–º Key values must be quoted, only Strings are allowed for keys. If you use other than String it will convert to String. But not recommended to use keys other than String's. Check an example like this - { 'key':'val' } over RFC 4627 - jsonformatter
var storage = {
0 : null,
1 : "Hello"
};
console.log( storage[1] ); // Hello
console.log( JSON.stringify( storage ) ); // {"0":null,"1":"Hello","2":"world!"}
var objLiteral = {'key1':'val1'};
var arr = [10, 20], arr2 = [ 'Yash', 'Sam' ];
var obj = { k: 'v' }, obj2 = { k2: 'v2' };
var fun = function keyFun() {} ;
objLiteral[ arr ] = 'ArrayVal'; objLiteral[ arr2 ] = 'OverridenArrayVal';
objLiteral[ obj ] = 'ObjectVal'; objLiteral[ obj2 ] = 'OverridenObjectVal';
objLiteral[ fun ] = 'FunctionVal';
console.log( objLiteral );
// Object {key1: "val1", 10,20: "ArrayVal", Yash,Sam: "OverridenArrayVal", [object Object]: "OverridenObjectVal", function keyFun() {}: "FunctionVal"}
console.log( JSON.stringify( objLiteral ) );
// {"key1":"val1","10,20":"ArrayVal","Yash,Sam":"OverridenArrayVal","[object Object]":"OverridenObjectVal","function keyFun() {}":"FunctionVal"}
console.log( JSON.parse( JSON.stringify( objLiteral ) ) );
// Object {key1: "val1", 10,20: "ArrayVal", Yash,Sam: "OverridenArrayVal", [object Object]: "OverridenObjectVal", function keyFun() {}: "FunctionVal"}
console.log('Accessing Array Val : ', objLiteral[ [10,20] ] );
console.log('Accessing Object Val : ', objLiteral[ '[object Object]' ] );
console.log('Accessing Function Val : ', objLiteral[ 'function keyFun() {}' ] );
â–º JSON Strings must be quoted with " and not '. A string is very much like a C or Java string. Strings should be wrapped in double quotes.
Literals are fixed values, not variables, that you literally provide in your script.
A string is a sequence of zero or more characters wrapped in quotes with backslash escapement, the same notation used in most programming languages.
🔫 - Special Symbols are allowed in String but not recomended to use.
" - Special characters can be escaped. But not recomended to escape (') Single Quotes.
In Strict mode it will throw and Error - SyntaxError: Unexpected token ' in JSON
Check with this code { "Hai\" \n Team 🔫":5, "Bye \'": 7 } over online JSON Edtions. Modes notStrict, Strinct.
var jsonString = "{'foo': 452}"; // {'foo': 452}
var jsonStr = '{"foo": 452}'; // {"foo": 452}
JSON.parse( jsonString ); // Unexpected token ' in JSON at position 1(…)
JSON.parse( jsonStr ); // Object {foo: 452}
objLiteral['key'] = 'val'; // Object {foo: 42, key: "val"}
objLiteral.key2 = 'val';
// objLiteral.key\n3 - SyntaxError: Invalid or unexpected token
objLiteral['key\n3'] = 'val'; // Object {"foo": "42", key: "val", key2: "val", "key↵3": "val"}
JSON.stringify( objLiteral ); // {"foo":"42","key":"val","key2":"val","key\n3":"val"}
Object Property accessors provide access to an object's properties by using the dot notation or the bracket notation.
â–º You have a more limited range of values (e.g. no functions allowed). A value can be a string in double quotes, number, boolean, null, object, or array. These structures can be nested.
var objLiteral = {};
objLiteral.funKey = function sayHello() {
console.log('Object Key with function as value - Its outcome message.');
};
objLiteral['Key'] = 'Val';
console.log('Object Literal Fun : ', objLiteral );
// Object Literal Fun : Object {Key: "Val"}Key: "Val"funKey: sayHello()__proto__: Object
console.log( JSON.stringify( objLiteral ) ); // {"Key":"Val"}
â–º JavaScript is the most popular implementation of the ECMAScript Standard.
The core features of Javascript are based on the ECMAScript standard, but Javascript also has other additional features that are not in the ECMA specifications/standard. Every browser has a JavaScript interpreter.
JavaScript is a dynamically typed language. That means you don't have to specify the data type of a variable when you declare it, and data types are converted automatically as needed during script execution.
Literals :
'37' - 7 // 30
'37' + 7 // "377"
+'37' + 7 // 44
+'37' // 37
'37' // "37"
parseInt('37'); // 37
parseInt('3.7'); // 3
parseFloat(3.7); // 3.7
// An alternative method of retrieving a number from a string is with the + (unary plus) operator:
+'3.7' // 3.7
Object literals RFC 7159
An object structure is represented as a pair of curly brackets surrounding zero or more name/value pairs (or members). A name is a
string. A single colon comes after each name, separating the name from the value. A single comma separates a value from a following
name. The names within an object SHOULD be unique.
ECMAScript supports prototype-based inheritance. Every constructor has an associated prototype, and every object created by that constructor has an implicit reference to the prototype (called the object’s
prototype) associated with its constructor. Furthermore, a prototype may have a non-null implicit reference to its prototype, and so on; this is called the prototype chain.
In a class-based object-oriented language, in general, state is carried by instances, methods are carried by classes, and inheritance is only of structure and behavior. In ECMAScript, the state and methods are carried by objects, and structure, behavior, and state are all inherited.
A prototype is an object used to implement structure, state, and behavior inheritance in ECMAScript. When a constructor creates an object, that object implicitly references the constructor’s associated prototype for the purpose of resolving property references. The constructor’s associated prototype can
be referenced by the program expression constructor.prototype, and properties added to an object’s prototype are shared, through inheritance, by all objects sharing the prototype.
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
For the ones who still think that RFC are more important than blogs and opinion based misconceptions, let's try to answer clarifying some points.
I'm not going to repeat all the correct differences already mentioned in previous answers, here I'm just trying adding value summarizing some crucial part rfc7159
Extracts from https://www.rfc-editor.org/rfc/rfc7159
JavaScript Object Notation (JSON) is a text format for the
serialization of structured data. It is derived from the object
literals of JavaScript, as defined in the ECMAScript Programming
Language Standard, Third Edition [ECMA-262].
JSON can represent four primitive types (strings, numbers, booleans,
and null) and two structured types (objects and arrays).
An object is an unordered collection of zero or more name/value
pairs, where a name is a string and a value is a string, number,
boolean, null, object, or array.
begin-object = ws %x7B ws ; { left curly bracket
end-object = ws %x7D ws ; } right curly bracket
A JSON value MUST be an object, array, number, or string, or one of
the following three literal names: false null true
An object structure is represented as a pair of curly brackets
The names within an object SHOULD be unique.
object = begin-object [ member *( value-separator member ) ]
end-object
An object whose names are all unique is interoperable in the sense
that all software implementations receiving that object will agree on
the name-value mappings. When the names within an object are not
unique, the behavior of software that receives such an object is
unpredictable.
Examples (from page 12 of RFC)
This is a JSON object:
{
"Image": {
"Width": 800,
"Height": 600,
"Title": "View from 15th Floor",
"Thumbnail": {
"Url": "http://www.example.com/image/481989943",
"Height": 125,
"Width": 100
},
"Animated" : false,
"IDs": [116, 943, 234, 38793]
}
}
Its Image member is an object whose Thumbnail member is an object and
whose IDs member is an array of numbers.
There is really no such thing as a "JSON Object".
Really?
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 }
Here is one surprising difference: you can not use undefined in json and all object fields with undefined values will disappear after JSON.stringify
let object = { "a": undefined } ;
let badJSON= '{ "a": undefined }';
console.log('valid JS object :', object );
console.log('JSON from object:', JSON.stringify(object) );
console.log('invalid json :', JSON.parse(badJSON) );
🙈🙉🙊
Javascript Object Literal vs JSON:
Object literal syntax is a very convenient way to create javascript objects
The JSON language, which stands for 'Javascript object notation', has its syntax derived from javascript object literal syntax. It is used as a programming language independent textual data transfer format.
Example:
JS object notation, used in JS to create objects in the code conveniently:
const JS_Object = {
1: 2, // the key here is the number 1, the value is the number 2
a: 'b', // the key is the string a, the value is the string b
func: function () { console.log('hi') }
// the key is func, the value is the function
}
Example of JSON:
{"widget": {
"debug": "on",
"window": {
"title": "Sample Konfabulator Widget",
"name": "main_window",
"width": 500,
"height": 500
},
"image": {
"src": "Images/Sun.png",
"name": "sun1",
"hOffset": 250,
"vOffset": 250,
"alignment": "center"
},
"text": {
"data": "Click Here",
"size": 36,
"style": "bold",
"name": "text1",
"hOffset": 250,
"vOffset": 100,
"alignment": "center",
"onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
}
}}
Main differences:
All object keys in JSON must be strings. In Javascript object keys can be strings or numbers
All strings in JSON must be quoted in "double quotes". Whereas in Javascript both single quotes and double quotes are allowed. Even with no quotes in the Javascript object notation the object keys are implicitly casted to strings.
In JSON a function cannot be defined as a value of an object (since this is Javascript specific). In Javascript this is completely legal.
Javascript build in JSON object:
JSON objects can be easily converted to Javascript and vice versa using the built in JSON object which Javascript offers in its runtime. For example:
const Object = {
property1: true,
property2: false,
}; // creating object with JS object literal syntax
const JSON_object = JSON.stringify(Object); // stringify JS object to a JSON string
console.log(JSON_object); // note that the (string) keys are in double quotes
const JS_object = JSON.parse(JSON_object); // parse JSON string to JS object
console.log(JS_object.property1, JS_object.property2);
// accessing keys of the newly created object