JSON – Introduction & Syntax
What is JSON?
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.
- JSON is plain text and language independent.
- JSON is used to send, receive, and store data.
- It can be easily converted to JavaScript objects and vice versa.
- Originally specified by Douglas Crockford.
Example
{
"name": "John",
"age": 30,
"car": null}
Defines an object with three properties:
"name"
→"John"
"age"
→30
"car"
→null
Why Use JSON?
- It’s lightweight and easy to transmit across networks.
- Text-only format, compatible with any programming language.
- Ideal for APIs and server communication.
- Stores complex data structures (objects and arrays).
JSON and JavaScript
JSON is syntactically identical to JavaScript object notation.
This means:
- JavaScript can easily parse JSON strings into objects.
- JavaScript can convert objects into JSON strings.
Built-in JavaScript JSON Methods
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 Rules
JSON syntax is derived from JavaScript object notation:
- Data is written as name/value pairs
- Pairs are separated by commas
- Curly braces
{}
hold objects - Square brackets
[]
hold arrays - Keys must be in double quotes
- No comments allowed
JSON Name/Value Pair Example
"name": "John"
"name"
→ key"John"
→ value
JSON Data Types
In JSON, values must be one of the following:
- String
- Number
- Object
- Array
- Boolean
- Null
Example:
{
"string": "Hello",
"number": 25,
"boolean": true,
"array": [1, 2, 3],
"object": { "key": "value" },
"nullValue": null}
Difference Between JSON and JavaScript Object
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}';
JSON Files
- File extension:
.json
- MIME type:
application/json