← Back to Chapters

JSON Introduction

? JSON Introduction

? Quick Overview

JSON (JavaScript Object Notation) is a lightweight data-interchange format used to exchange data between client and server in web applications.

? Key Concepts

  • Text-based data format
  • Language independent
  • Easy to read and write

? Syntax / Theory

  • Key/value pairs
  • Keys in double quotes
  • Supports arrays, objects, numbers, strings, booleans, null
? View Code Example
// JSON object structure example
{
"name":"John",
"age":30,
"isStudent":false,
"skills":["PHP","JavaScript","MySQL"],
"address":{"city":"New York","zip":"10001"}
}

? Using JSON in JavaScript

? View Code Example
// Converting JSON string to JavaScript object and back
let jsonString='{"name":"Alice","age":25}';
let obj=JSON.parse(jsonString);
console.log(obj.name);
let newJson=JSON.stringify(obj);
console.log(newJson);

? JSON with PHP

? View Code Example
// Encoding and decoding JSON in PHP
<?php
$data=array("name"=>"Bob","age"=>28,"skills"=>array("PHP","Laravel"));
echo json_encode($data);
$jsonString='{"name":"Eve","age":22}';
print_r(json_decode($jsonString,true));
?>

? Use Cases

  • API responses
  • Configuration files
  • AJAX data transfer

✅ Tips & Best Practices

  • Validate JSON before parsing
  • Use proper content-type headers

? Try It Yourself

  • Create a JSON file and load it using fetch()
  • Send JSON data to PHP via AJAX
  • Convert PHP arrays to JSON