JavaScript JSON

JSON (JavaScript Object Notation) is a lightweight format for storing and exchanging data. It’s based on JavaScript objects but can be used by any programming language. It’s everywhere in web development for APIs and data storage.

What is JSON?

JSON is a text format that represents data as key-value pairs, similar to JavaScript objects. But JSON has strict rules:

  • Keys must be strings in double quotes
  • Values can be strings, numbers, booleans, null, objects, or arrays
  • No functions or undefined values
  • Uses double quotes only

Example JSON:

{
  "name": "John",
  "age": 30,
  "isStudent": false,
  "hobbies": ["reading", "coding"],
  "address": {
    "street": "123 Main St",
    "city": "Anytown"
  }
}

JSON vs JavaScript Objects

JavaScript objects are flexible, but JSON is more restrictive for data exchange:

// JavaScript object
let person = {
  name: "John", // Single quotes OK
  age: 30,
  greet() { // Functions OK
    console.log("Hello");
  },
  undefinedProp: undefined // OK in JS, not in JSON
};

// JSON string
let jsonString = '{"name": "John", "age": 30}';

Learn more about JavaScript objects in JavaScript arrays and objects.

Converting to JSON: JSON.stringify()

To send data to a server or store it, convert JavaScript objects to JSON strings:

let user = {
  name: "Alice",
  age: 25,
  hobbies: ["painting", "music"]
};

let jsonString = JSON.stringify(user);
console.log(jsonString); // '{"name":"Alice","age":25,"hobbies":["painting","music"]}'
console.log(typeof jsonString); // "string"

You can format it nicely:

let formatted = JSON.stringify(user, null, 2);
console.log(formatted);
/*
{
  "name": "Alice",
  "age": 25,
  "hobbies": [
    "painting",
    "music"
  ]
}
*/

The third parameter (2) adds indentation.

Converting from JSON: JSON.parse()

When you receive JSON data, convert it back to JavaScript objects:

let jsonData = '{"name":"Bob","age":28,"active":true}';
let userObject = JSON.parse(jsonData);

console.log(userObject.name); // "Bob"
console.log(userObject.age); // 28
console.log(typeof userObject); // "object"

Working with APIs

JSON is the standard for web APIs. Here’s how you might fetch data:

fetch('https://api.example.com/users')
  .then(response => response.json()) // Automatically parses JSON
  .then(data => {
    console.log(data); // JavaScript object
  })
  .catch(error => {
    console.error('Error fetching data:', error);
  });

Or manually:

let response = await fetch('https://api.example.com/users');
let jsonString = await response.text();
let users = JSON.parse(jsonString);

Common JSON Patterns

API Response

{
  "success": true,
  "data": [
    {"id": 1, "name": "User 1"},
    {"id": 2, "name": "User 2"}
  ],
  "total": 2
}

Configuration

{
  "database": {
    "host": "localhost",
    "port": 5432,
    "name": "myapp"
  },
  "features": {
    "darkMode": true,
    "notifications": false
  }
}

Error Handling

JSON operations can fail:

let invalidJson = '{"name": "John", "age":}'; // Missing value

try {
  let parsed = JSON.parse(invalidJson);
} catch (error) {
  console.log('Invalid JSON:', error.message);
}

Always wrap JSON.parse() in try-catch for safety.

Storing Data Locally

Use JSON with localStorage:

let settings = { theme: 'dark', language: 'en' };

// Save
localStorage.setItem('settings', JSON.stringify(settings));

// Load
let savedSettings = JSON.parse(localStorage.getItem('settings'));

This persists data between browser sessions.

JSON is fundamental for modern web apps. Practice by working with real APIs and storing user preferences.

For more on asynchronous operations like fetching data, see JavaScript promises and async/await.

The MDN JSON reference covers all JSON methods in detail.

Last updated on