OnlineCBT Logo OnlineCBT
JavaScript Tutorial
JAVASCRIPT · LESSON 34

Working with JSON (parse & stringify)

By Ratan Updated: 16 Oct 2026

Convert JavaScript objects to JSON strings and parse incoming API JSON payloads.

Level: Beginner to Advanced
Duration: ~60 Mins Deep-Dive

Exchange a data format, not executable code

JSON represents objects, arrays, strings, numbers, booleans and null in a text format. JSON.parse converts valid JSON text into JavaScript values. JSON.stringify serializes supported values. JSON is not the same syntax as an arbitrary JavaScript object literal.

const student = { name: 'Asha', score: 82, passed: true };
const text = JSON.stringify(student);
console.log(text); // {"name":"Asha","score":82,"passed":true}
const restored = JSON.parse(text);
console.log(restored.score); // 82

JSON property names and strings use double quotes. Comments, trailing commas and undefined are not valid JSON values. Never replace JSON.parse with eval to accept an untrusted response.

Validate after parsing

function readProgress(text) {
  const value = JSON.parse(text);
  if (value === null || typeof value !== 'object' || Array.isArray(value)
      || !Number.isInteger(value.completed) || value.completed < 0) {
    throw new TypeError('Invalid progress record');
  }
  return { completed: value.completed };
}
console.log(readProgress('{"completed":3}')); // { completed: 3 }

Valid JSON can still have the wrong shape. A successful parse does not establish that a payload is a permitted user, safe HTML or a trustworthy authorization claim.

Serialization limitations

Object properties whose values are undefined or functions are omitted; such array entries serialize differently, commonly as null. Date normally serializes to a string. Circular references throw, and BigInt needs an explicit representation strategy. Map, Set and class prototypes do not round-trip as their original types automatically.

Numbers and copies

Large JSON numbers can lose precision when parsed into Number. Use a documented string representation for identifiers that must remain exact. stringify/parse is therefore not a universal deep-clone technique; choose a method matching the actual data types.

Practice

  1. Parse malformed JSON inside try/catch and show a useful recovery state.
  2. Test readProgress with null, an array and a negative count.
  3. Serialize a Date and inspect the restored type.
  4. Compare a missing object property with an explicit null property in serialized output.

📝 Live Lesson Practice

HTML/CSS JavaScript Python C++ C PHP
⌨️ Practice Inputs (लाइव इनपुट भरें) (खाली होने पर RED, भरने पर GREEN underline)
💻 Code Editor (Monaco VS Code Engine)
👀 Live Preview
पता संपर्क करें

+91 7877547686

ई-मेल

onlinecbtportal@gmail.com

हेल्पलाइन नंबर

+91 7877547686


डाउनलोड करने के लिए क्लिक करें
Get it on Google Play

ऐप डाउनलोड करने
के लिए Google Play पर
उपलब्ध है

WhatsApp Chat