The JavaScript Object Notation
6 min read·Jan 1, 2025
The JavaScript Object Notation (JSON) is a language-agnostic data format used to store collections of data in the form of key-value pairs, that is easy for humans to read and write, and easy for machines to parse and generate.
It is commonly used to create configuration files, exchange data between applications, or store data in databases.
Although relatively similar to object literals, JSON objects are only meant to store data and do not allow for computed property names or additional properties, such as methods.
The JSON syntax
Similar to object literals, JSON objects are declared using angle brackets:
variable = {};
JSON property keys must be enclosed in double quotes and properties themselves separated by comma characters:
{
"key": "value",
"key": value,
...
}
The JSON data types
JSON supports the following data types:
- String: Enclosed in double quotes (e.g.,
"Hello"). - Number: Integer or floating-point (e.g.,
42,3.14). - Boolean:
trueorfalse. - Null:
null. - Object: Enclosed in curly braces
{}. - Array: Enclosed in square brackets
[].
For example:
{
"id": 1,
"name": "John Doe",
"email": "jdoe@mail.com",
"roles": ["admin", "user"],
"active": true,
"settings": {
"theme": null,
"language": "en-us"
}
}
Convert object literals into JSON strings
To convert a JavaScript object into a JSON string, you can use the global built-in JSON.stringify method as follows:
string = JSON.stringify(object);
Note: When stringifying an object, all methods will automatically be ignored.
Example
Let's consider this script:
const userObject = {
id: 1,
name: 'John Doe',
setName: function(name) {
this.name = name;
}
};
const jsonString = JSON.stringify(userObject);
console.log(jsonString);
When executed, it will convert the userObject object literal into a string and remove the setName property.
Which will produce this output:
{"id":1,"name":"John Doe"}
Convert JSON strings into object literals
To convert a JSON string into a usable JavaScript object, you can use the global built-in JSON.parse method as follows:
object = JSON.parse(string);
Example
Let's consider this script:
const jsonString = '{"id":1,"name":"John Doe"}';
const userObject = JSON.parse(jsonString);
console.log(userObject.id);
console.log(userObject.name);
When executed, it will convert the jsonString string into a usable object literal.
Which will produce this output:
1
John Doe
Enjoying the courses?
I've made these courses completely free so anyone can learn from them. If they've helped you and you'd like to actively support the work behind BackendBrewery, you can leave a tip:
Support BackendBrewery