
All About JavaScript JSON
What is JSON?
JSON stands for JavaScript Object Notation. It is a text-based data format that is used to store and transfer data.
In JSON, the data are in key/value pairs separated by a comma ,
.
JSON Data
JSON data consists of key/value pairs similar to JavaScript object properties.
- The key and values are written in double quotes separated by a colon
":"
. - JSON data requires double quotes for the key.
{
"name": "John",
"age": 30,
"city": "New York"
}
JSON Object
The JSON object is written inside curly braces { }
. JSON objects can contain multiple key/value pairs.
{
"employee": {
"name": "John",
"age": 30,
"city": "New York"
}
}
JSON Array
JSON array is written inside square brackets [ ]
. JSON data can contain objects and arrays.
However, unlike JavaScript objects, JSON data cannot contain functions as values.
{
"employees": [
{ "name": "John", "age": 30, "city": "New York" },
{ "name": "Anna", "age": 22, "city": "London" },
{ "name": "Peter", "age": 40, "city": "Paris" }
]
}
JavaScript Objects and JSON
JavaScript Objects and JSON are not the same.
- Though the syntax of JSON is similar to the JavaScript object, JSON is different from JavaScript objects.
- JSON: The key in key/value pair should be in double quotes.
- JavaScript Object: The key in key/value pair can be without double quotes.
- JSON cannot contain functions.
- JSON can be created and used by other programming languages.
- JavaScript objects can contain functions.
- JavaScript objects can only be used in JavaScript.
// JSON Example
{
"name": "John",
"age": 30
}
// JavaScript Object Example
const person = {
name: "John",
age: 30,
greet: function() { console.log("Hello!"); }
};
Accessing JSON Data
You can access JSON data using the dot notation or square bracket syntax []
.
const jsonData = {
"name": "John",
"age": 30,
"city": "New York"
};
// Using dot notation
console.log(jsonData.name); // John
// Using bracket notation
console.log(jsonData["age"]); // 30
Converting JSON to Object
You can convert JSON data to a JavaScript object using the built-in JSON.parse()
function.
const jsonString = '{"name": "John", "age": 30, "city": "New York"}';
const jsonObject = JSON.parse(jsonString);
console.log(jsonObject.name); // John
Converting Object to JSON
You can also convert JavaScript objects to JSON format using the JavaScript built-in JSON.stringify()
function.
const person = {
name: "John",
age: 30,
city: "New York"
};
const jsonString = JSON.stringify(person);
console.log(jsonString); // {"name":"John","age":30,"city":"New York"}
Like, Share and Subscribe #DevTools99 for more useful videos, tools info and tutorials . Thank you!