learn2kode.in

JavaScript JSON tutorial for beginners

JSON (JavaScript Object Notation) is a lightweight data format used to store and exchange data between a client (browser) and a server. It is easy to read, write, and understand, and works with almost every programming language. JSON looks very similar to JavaScript objects, but it is text-based.

Why is JSON Important?

JSON is widely used for:
Almost all modern web applications rely on JSON.

JSON Syntax Rules

JSON follows strict rules:
JSON Syntax Rules
JSON Example
{
  "name": "learn2kode",
  "age": 25,
  "isDeveloper": true,
  "skills": ["HTML", "CSS", "JavaScript"]
}

JSON vs JavaScript Object

Feature JSON JavaScript Object
Format Text Object
Quotes Double quotes only Single or double quotes
Functions allowed ❌ No ✔ Yes
Used for APIs ✔ Yes ❌ No

Converting JSON ↔ JavaScript

JSON.parse() – JSON to JavaScript Object
let jsonData = '{"name":"Mani","age":25}';
let obj = JSON.parse(jsonData);

console.log(obj.name); // Mani
JSON.stringify() – JavaScript Object to JSON
let user = {
  name: "Mani",
  age: 25
};

let jsonString = JSON.stringify(user);
console.log(jsonString);

JSON Arrays

JSON can store arrays of objects:
[
  { "id": 1, "course": "HTML" },
  { "id": 2, "course": "JavaScript" }
]

JSON with APIs (Real-World Example)

When you fetch data from an API, it usually returns JSON:
fetch("https://api.example.com/users")
  .then(response => response.json())
  .then(data => console.log(data));

Common JSON Errors to Avoid

When to Use JSON

Key Takeaways