JSON (JavaScript Object Notation)
JSON
(JavaScript Object Notation) is a data interchange format for storing and exchanging information.
The format represents data using curly braces { }
or square brackets [ ]
, consisting of key-value pairs. The keys are wrapped in double quotes with values made up of strings, numbers, etc.
{
"name": "CodeFriends",
"address": {
"city": "New York"
},
"age": 20
}
Commas (,) are used to separate multiple key-value pairs within an object, but no comma should follow the last key-value pair.
Although JSON is based on the way JavaScript creates objects, it is language-independent and can be used with most programming languages.
It is widely used for data interaction between servers and web pages in most applications.
Basic Structure of JSON
JSON can only be expressed as an object or an array.
1. Object
A collection of key-value pairs wrapped in curly braces { }
.
{
"Key1": "Value1",
"Key2": "Value2",
...
}
{
"name": "CodeFriends",
"age": 25
}
2. Array
A list of values wrapped in square brackets [ ]
.
["Value1", "Value2", "..."]
["Apple", "Banana", "Cherry"]
Handling JSON in JavaScript
JavaScript provides a built-in JSON
object to handle JSON data.
The JSON
object has methods to convert JSON data into a string or a JavaScript object.
1. JSON.stringify()
Converts JavaScript objects or values into a JSON string.
const obj = {
name: 'CodeFriends',
age: 25,
};
const jsonString = JSON.stringify(obj);
console.log(jsonString); // '{"name":"CodeFriends","age":25}' output
2. JSON.parse()
Converts a JSON string back into a JavaScript object or value.
const jsonString = '{"name":"CodeFriends","age":25}';
const obj = JSON.parse(jsonString);
console.log(obj.name); // "CodeFriends" output
Points to Note
-
Keys used as property names in JSON must always be wrapped in double quotes ("). While JavaScript objects allow single quotes ('), JSON does not.
-
Data types that are not supported by JSON (e.g., functions,
undefined
) cannot be converted to JSON.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.