JSON Tutorial

What is JSON?

JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write and easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language.

JSON Syntax

{
    "name": "John Doe",
    "age": 30,
    "isStudent": false,
    "address": {
        "street": "123 Main St",
        "city": "New York"
    },
    "hobbies": ["reading", "gaming", "coding"]
}
  • Data is in name/value pairs
  • Data is separated by commas
  • Curly braces hold objects
  • Square brackets hold arrays

JSON Data Types

String

"name": "John Doe"

Number

"age": 30

Boolean

"isStudent": false

Array

"hobbies": ["reading", "gaming"]

JSON Best Practices

  • Use meaningful key names
  • Keep the structure consistent
  • Validate your JSON data
  • Use proper indentation for readability
  • Handle special characters properly

Common JSON Operations

Parsing JSON

const jsonString = '{"name":"John"}';
const obj = JSON.parse(jsonString);
console.log(obj.name); // Output: John

Stringifying JSON

const obj = {name: "John"};
const jsonString = JSON.stringify(obj);
console.log(jsonString); // Output: {"name":"John"}