- JSON stands for JavaScript Object Notation.
- JSON is a string not a JavaScript object.
JSON is a specification for formatting a text string so it can represent structured data. JavaScript objects can be converted to JSON strings and vice-versa but with limitations. - functions are not allowed in JSON strings.
If an object is converted it’s functions are simply omitted from the string. - Object keys must be strings enclosed in double quotes
"
. - An object value can be a string, number, JSON object, array, true, false, or null.
People confuse JavaScript object literal syntax with JSON because they look very similar, but if you’re writing JavaScript source code and not defining a string, you’re not dealing with JSON. JSON is a textual, language-independent data-exchange serialization specification for encoding data structures into a string, much like XML, CSV or YAML.
var obj = {foo: 22}; // Defines a JavaScript object (this is *not* JSON)
var json = '{"foo": 22}'; // Defines a JSON string
You may be working with an object derived from a JSON string, but JSON must first be parsed into a language object before it can be used. Likewise, an object needs to be converted to a JSON string before it can be sent via AJAX or saved to a database or file.
More Resources
- What is the difference between JSON and Object Literal Notation?
- There’s no such thing as a “JSON Object”
Create a string from an object
A JSON string can be created from a JavaScript object using the JSON.stringify
method.
See a live demo.
// Define a JavaScript object.
var customer_object = {
'user_name': 'Bob',
'user_id': '24735',
'likes': [{
'0': 'Walking',
'1': 'Trees'
}],
'total_purchases': '6',
'dislikes': [{
'0': 'Biking'
}]
};
// Convert the object into a JSON string.
var customer_json = JSON.stringify(customer_object);
If the object has a function definition, the function is simply omitted when it’s converted to a string.
Create an object from a string
A JavaScript object can be created from a JSON string using the JSON.parse
method.
See a live demo.
// Define a JSON string.
var customer_json = '{"user_name":"Bob","user_id":24735,"likes":[{"0":"Walking","1":"Trees"}],"total_purchases":6,"dislikes":[{"0":"Biking"}]}';
// Convert the JSON string into a JavaScript object.
var customer_object = JSON.parse(customer_json);