Tutorials Logic, IN +91 8092939553 info@tutorialslogic.com
FAQs Support
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Interview Questions Website Development
Compiler Tutorials

JSON and AJAX

What is JSON?

JSON (JavaScript Object Notation) is a lightweight, text-based data format that is easy for humans to read and write, and easy for machines to parse and generate. It is the de facto standard for data exchange in modern AJAX applications.

JSON supports six data types: string, number, boolean, null, object, and array.

JSON.stringify() and JSON.parse()
// JavaScript object → JSON string (for sending to server)
const user = {
  name: 'Alice',
  age: 30,
  active: true,
  roles: ['admin', 'editor'],
  address: { city: 'New York', zip: '10001' }
};

const jsonString = JSON.stringify(user);
console.log(jsonString);
// '{"name":"Alice","age":30,"active":true,"roles":["admin","editor"],"address":{"city":"New York","zip":"10001"}}'

// Pretty-print with indentation (useful for debugging)
console.log(JSON.stringify(user, null, 2));

// JSON string → JavaScript object (after receiving from server)
const received = '{"id":1,"title":"Hello","published":true}';
const post = JSON.parse(received);
console.log(post.title); // "Hello"
console.log(typeof post); // "object"

// JSON.parse with error handling
try {
  const bad = JSON.parse('{ invalid json }');
} catch (e) {
  console.error('Parse error:', e.message);
}

Sending and Receiving JSON in AJAX

Sending JSON with Fetch and Receiving JSON
// Sending JSON to the server
const payload = {
  username: 'alice',
  email: 'alice@example.com',
  preferences: { theme: 'dark', notifications: true }
};

fetch('/api/users', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',  // REQUIRED when sending JSON
    'Accept': 'application/json'         // Tell server we expect JSON back
  },
  body: JSON.stringify(payload)          // Convert object to JSON string
})
  .then(res => {
    if (!res.ok) throw new Error(`HTTP ${res.status}`);
    return res.json();                   // Parse JSON response
  })
  .then(data => {
    console.log('Server response:', data);
    // data is already a JS object — no JSON.parse() needed
    console.log('New user ID:', data.id);
  })
  .catch(err => console.error('Error:', err));

JSON vs XML Comparison

FeatureJSONXML
VerbosityCompactVerbose (opening/closing tags)
ReadabilityEasy to readHarder to read
ParsingNative JS (JSON.parse)Requires DOMParser
Data typesSupports arrays, booleans, nullEverything is a string
CommentsNot supportedSupported
Schema validationJSON SchemaXSD, DTD
Usage todayDominant in REST APIsLegacy systems, SOAP
Common JSON Pitfalls
// ---- Pitfall 1: undefined values are dropped ----
const obj = { name: 'Alice', score: undefined, active: true };
console.log(JSON.stringify(obj));
// '{"name":"Alice","active":true}' — score is gone!

// ---- Pitfall 2: Circular references throw an error ----
const a = {};
const b = { ref: a };
a.ref = b; // circular!
try {
  JSON.stringify(a); // throws TypeError
} catch (e) {
  console.error('Circular reference:', e.message);
}

// ---- Pitfall 3: Dates become strings ----
const event = { name: 'Launch', date: new Date() };
const str = JSON.stringify(event);
const parsed = JSON.parse(str);
console.log(typeof parsed.date); // "string" — not a Date object!
// Fix: convert back manually
const realDate = new Date(parsed.date);

// ---- Pitfall 4: JSON keys must be double-quoted strings ----
// Valid JSON:   { "name": "Alice" }
// Invalid JSON: { name: 'Alice' }  ← single quotes and unquoted keys

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.