📘 Lesson  ·  Lesson 31

JSON

JSON

What JSON Is

// A JavaScript object (real code):
let student = { name: "Aman", marks: 85 };

// JSON — the same data as a STRING, for sending/storing:
'{"name": "Aman", "marks": 85}'
JSON (JavaScript Object Notation) is a text format for storing and sending data. It looks almost exactly like a JavaScript object, but it's a plain STRING — which means it can travel across the internet, be saved in a file, or stored in a database. When your web page asks a server for data, the server almost always replies with JSON. It's the universal language of data exchange on the web, understood by every programming language, not just JavaScript. Learning it takes ten minutes; you'll use it forever.

JSON Syntax Rules — stricter than JavaScript

// ✓ Valid JSON:
{
    "name": "Aman",
    "marks": 85,
    "passed": true,
    "subjects": ["Maths", "Science"],
    "address": { "city": "Aligarh" }
}

// ✗ INVALID JSON:
{
    name: "Aman",           // keys MUST be in double quotes
    'city': 'Aligarh',      // single quotes not allowed
    greet: function() {},   // no functions allowed
    marks: 85,              // no trailing comma allowed
}
JSON looks like a JavaScript object but follows stricter rules. First: keys must be wrapped in DOUBLE quotes — not single quotes, not bare. Strings must use double quotes too. Second: JSON holds only DATA — strings, numbers, booleans, null, arrays, and objects. No functions, no undefined, no comments. Third: no trailing comma after the last item. These restrictions exist because JSON must be readable by every language, so it keeps only the universal pieces. Most JSON errors you'll hit come from single quotes or missing quotes on keys.

JSON.stringify() — object to JSON string

let student = { name: "Aman", marks: 85 };

let json = JSON.stringify(student);
console.log(json);            // '{"name":"Aman","marks":85}'
console.log(typeof json);     // "string"  ← it's text now!

// Pretty-print with indentation (great for debugging):
JSON.stringify(student, null, 2);
/*  {
      "name": "Aman",
      "marks": 85
    }  */
JSON.stringify() converts a JavaScript object into a JSON string — that's how you prepare data to SEND to a server or save it. Notice the result's typeof is "string": all the object structure is now just text. A useful trick: pass null, 2 as extra arguments to get nicely indented output, which makes debugging much easier. Anything JSON can't represent (like a function property) is silently dropped during stringify — worth knowing when a property mysteriously vanishes.

JSON.parse() — JSON string back to object

let json = '{"name":"Aman","marks":85}';

let student = JSON.parse(json);
console.log(student.name);       // "Aman"   ← now a real object again
console.log(typeof student);     // "object"

// ✗ Invalid JSON throws an error — always guard it:
try {
    JSON.parse("not valid json");
} catch (e) {
    console.log("Invalid JSON!");
}
JSON.parse() does the reverse: it turns a JSON string back into a usable JavaScript object — that's how you handle data RECEIVED from a server. Once parsed, you can access properties normally with student.name. The pair is easy to remember: stringify = object → string (to send); parse = string → object (to use). Important: if the string isn't valid JSON, parse throws an error and crashes your script, so real code wraps it in try...catch (a technique you'll cover in the Modern JS group).

Where JSON Is Used

// 1. Receiving data from an API (the most common use):
//    A server sends: '[{"name":"Aman"},{"name":"Priya"}]'
let students = JSON.parse(response);
students.forEach(s => console.log(s.name));

// 2. Storing data in the browser (localStorage only holds strings):
localStorage.setItem("user", JSON.stringify({ name: "Aman" }));
let user = JSON.parse(localStorage.getItem("user"));

// 3. Config files, databases, and communication between languages
JSON appears everywhere in real development. APIs return JSON — every weather app, every social feed, every product listing you've ever seen fetched JSON from a server (you'll do this yourself in the AJAX tutorial). localStorage can only store strings, so you stringify objects going in and parse them coming out. And because every language reads JSON, it's how a PHP backend hands data to a JavaScript frontend. Master stringify and parse, and you can move data anywhere.

Exam Corner

Q: What is JSON? A text format for storing and exchanging data, based on JavaScript object syntax.

Q: Name two JSON syntax rules that differ from JavaScript objects. Keys must be in double quotes; no functions, comments, or trailing commas.

Q: What does JSON.stringify() do? Converts a JavaScript object into a JSON string.

Q: What does JSON.parse() do? Converts a JSON string back into a JavaScript object.

Q: Why is JSON needed for localStorage? Because localStorage can only store strings, not objects.

JSON क्या है

// JavaScript object (asli code):
let student = { name: "Aman", marks: 85 };

// JSON — vahi data STRING ke roop me, bhejne/rakhne ko:
'{"name": "Aman", "marks": 85}'
JSON (JavaScript Object Notation) data रखने और भेजने का text format है. यह लगभग बिल्कुल JavaScript object जैसा दिखता है, पर यह सादी STRING है — मतलब यह internet पर सफर कर सकता है, file में save हो सकता है, या database में रखा जा सकता है. जब आपका web page server से data मांगता है, server लगभग हमेशा JSON से जवाब देता है. यह web पर data आदान-प्रदान की सार्वभौमिक भाषा है, हर programming language समझती है, सिर्फ JavaScript नहीं. इसे सीखने में दस मिनट लगते हैं; आप इसे हमेशा use करेंगे.

JSON Syntax Rules — JavaScript से सख्त

// ✓ Valid JSON:
{
    "name": "Aman",
    "marks": 85,
    "passed": true,
    "subjects": ["Maths", "Science"],
    "address": { "city": "Aligarh" }
}

// ✗ INVALID JSON:
{
    name: "Aman",           // keys DOUBLE quotes me hone chahiye
    'city': 'Aligarh',      // single quotes allowed nahi
    greet: function() {},   // functions allowed nahi
    marks: 85,              // aakhri comma allowed nahi
}
JSON JavaScript object जैसा दिखता है पर सख्त rules follow करता है. पहला: keys DOUBLE quotes में लिपटी होनी चाहिए — single quotes नहीं, बिना quotes नहीं. Strings को भी double quotes चाहिए. दूसरा: JSON सिर्फ DATA रखता है — strings, numbers, booleans, null, arrays, और objects. कोई functions नहीं, कोई undefined नहीं, कोई comments नहीं. तीसरा: आखिरी item के बाद कोई trailing comma नहीं. ये पाबंदियां इसलिए हैं क्योंकि JSON को हर language पढ़ पाए, तो यह सिर्फ सार्वभौमिक टुकड़े रखता है. आपको मिलने वाली ज़्यादातर JSON errors single quotes या keys पर गायब quotes से आती हैं.

JSON.stringify() — object से JSON string

let student = { name: "Aman", marks: 85 };

let json = JSON.stringify(student);
console.log(json);            // '{"name":"Aman","marks":85}'
console.log(typeof json);     // "string"  ← ab yeh text hai!

// Indentation ke saath pretty-print (debugging ke liye badhiya):
JSON.stringify(student, null, 2);
/*  {
      "name": "Aman",
      "marks": 85
    }  */
JSON.stringify() JavaScript object को JSON string में बदलता है — ऐसे ही आप data server को BHEJNE या save करने को तैयार करते हैं. नतीजे का typeof "string" ध्यान दीजिए: सारी object structure अब बस text है. उपयोगी trick: सुंदर indented output पाने को अतिरिक्त arguments के रूप में null, 2 भेजिए, जो debugging बहुत आसान बनाता है. JSON जो नहीं दर्शा सकता (जैसे function property) वह stringify के दौरान चुपचाप गिर जाता है — जब कोई property रहस्यमय ढंग से गायब हो तब जानने लायक.

JSON.parse() — JSON string वापस object में

let json = '{"name":"Aman","marks":85}';

let student = JSON.parse(json);
console.log(student.name);       // "Aman"   ← ab phir asli object
console.log(typeof student);     // "object"

// ✗ Invalid JSON error phenkta hai — hamesha guard kariye:
try {
    JSON.parse("not valid json");
} catch (e) {
    console.log("Invalid JSON!");
}
JSON.parse() उल्टा करता है: यह JSON string को इस्तेमाल लायक JavaScript object में वापस बदलता है — ऐसे ही आप server से MILE data संभालते हैं. Parse होने के बाद, आप student.name से सामान्य रूप से properties access कर सकते हैं. जोड़ी याद रखना आसान: stringify = object → string (भेजने को); parse = string → object (use करने को). ज़रूरी: अगर string valid JSON न हो, parse error फेंककर आपकी script गिरा देता है, तो असली code इसे try...catch में लपेटता है (Modern JS group में cover की तकनीक).

JSON कहां use होता है

// 1. API se data lena (sabse common):
//    Server bhejta hai: '[{"name":"Aman"},{"name":"Priya"}]'
let students = JSON.parse(response);
students.forEach(s => console.log(s.name));

// 2. Browser me data rakhna (localStorage sirf strings rakhta hai):
localStorage.setItem("user", JSON.stringify({ name: "Aman" }));
let user = JSON.parse(localStorage.getItem("user"));

// 3. Config files, databases, aur languages ke beech baatcheet
JSON असली development में हर जगह दिखता है. APIs JSON लौटाते हैं — हर weather app, हर social feed, हर product listing जो आपने देखी server से JSON लाई (आप AJAX tutorial में खुद यह करेंगे). localStorage सिर्फ strings रख सकता है, तो आप जाते objects stringify करते हैं और आते parse. और क्योंकि हर language JSON पढ़ती है, ऐसे ही PHP backend JavaScript frontend को data सौंपता है. stringify और parse master कीजिए, और आप data कहीं भी ले जा सकते हैं.

Exam Corner

Q: JSON क्या है? Data रखने और आदान-प्रदान का text format, JavaScript object syntax पर आधारित.

Q: JavaScript objects से अलग दो JSON syntax rules बताइए. Keys double quotes में होनी चाहिए; कोई functions, comments, या trailing commas नहीं.

Q: JSON.stringify() क्या करता है? JavaScript object को JSON string में बदलता है.

Q: JSON.parse() क्या करता है? JSON string को वापस JavaScript object में बदलता है.

Q: localStorage के लिए JSON क्यों चाहिए? क्योंकि localStorage सिर्फ strings रख सकता है, objects नहीं.
← Back to JavaScript Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

इस पेज का code यहाँ तैयार है — बदलिए और तुरंत नतीजा देखिए. कुछ install किए बिना.
👁 Live Preview
सब कुछ आपके browser में ही चलता है — कोई server, कोई signup नहीं. JavaScript का console.log देखने के लिए F12 दबाइए.