Clean β’ Professional
JSON (JavaScript Object Notation) is a lightweight text format used for storing and exchanging data between a client and a server.
It is easy to read and write, and its syntax is similar to JavaScript objects.
Example
{
"name": "John",
"age": 30,
"car": null}
Defines an object with three properties:
"name" β "John""age" β 30"car" β nullJSON is syntactically identical to JavaScript object notation.
This means:
| Method | Description | Example |
|---|---|---|
JSON.parse() | Converts JSON string β JavaScript object | const obj = JSON.parse(text); |
JSON.stringify() | Converts JavaScript object β JSON string | const text = JSON.stringify(obj); |
Example:
let text = '{"name":"John", "age":30}';
const obj = JSON.parse(text);
console.log(obj.name); // John
const jsonString = JSON.stringify(obj);
console.log(jsonString); // {"name":"John","age":30}
JSON Example with Array
{
"employees": [
{ "firstName": "John", "lastName": "Doe" },
{ "firstName": "Anna", "lastName": "Smith" },
{ "firstName": "Peter", "lastName": "Jones" }
]
}
Accessing data in JavaScript:
const obj = JSON.parse(text);
console.log(obj.employees[1].firstName); // Anna
JSON syntax is derived from JavaScript object notation:
{} hold objects[] hold arrays"name": "John"
"name" β key"John" β valueIn JSON, values must be one of the following:
Example:
{
"string": "Hello",
"number": 25,
"boolean": true,
"array": [1, 2, 3],
"object": { "key": "value" },
"nullValue": null}
| Feature | JavaScript Object | JSON |
|---|---|---|
| Keys | Can be unquoted | Must be in double quotes |
| Values | Can include functions, dates, undefined | Only strings, numbers, objects, arrays, booleans, or null |
| Comments | Allowed | Not allowed |
Example:
// JavaScript Object
let obj = { name: "John", age: 30 };
// JSON String
let json = '{"name":"John", "age":30}';
.jsonapplication/json