Try JSON Editor

JSON in JavaScript: Complete Guide with Examples

Master JSON in JavaScript! Learn how to parse, stringify, and work with JSON data in JavaScript applications. Includes real-world examples and best practices.

What is JSON in JavaScript?

JSON (JavaScript Object Notation) is natively supported in JavaScript. The JSON object provides two key methods for working with JSON data:

JSON.parse() - Converting JSON to JavaScript Objects

Basic Usage

// JSON string
const jsonString = '{"name":"John","age":30,"city":"New York"}';

// Parse JSON to JavaScript object
const user = JSON.parse(jsonString);

console.log(user.name);  // Output: John
console.log(user.age);   // Output: 30

Parsing Arrays

const jsonArray = '[{"id":1,"name":"Product 1"},{"id":2,"name":"Product 2"}]';
const products = JSON.parse(jsonArray);

products.forEach(product => {
  console.log(`${product.id}: ${product.name}`);
});

Error Handling with try-catch

function safeParseJSON(jsonString) {
  try {
    return JSON.parse(jsonString);
  } catch (error) {
    console.error('Invalid JSON:', error.message);
    return null;
  }
}

const data = safeParseJSON('{"invalid json}');  // Returns null

JSON.stringify() - Converting JavaScript to JSON

Basic Usage

const user = {
  name: "John Doe",
  age: 30,
  email: "john@example.com"
};

// Convert to JSON string
const jsonString = JSON.stringify(user);
console.log(jsonString);
// Output: {"name":"John Doe","age":30,"email":"john@example.com"}

Pretty Printing with Indentation

const user = { name: "John", age: 30, hobbies: ["reading", "coding"] };

// Pretty print with 2-space indentation
const prettyJSON = JSON.stringify(user, null, 2);
console.log(prettyJSON);
/*
{
  "name": "John",
  "age": 30,
  "hobbies": [
    "reading",
    "coding"
  ]
}
*/

Filtering Properties with Replacer

const user = {
  name: "John",
  password: "secret123",  // Don't want to include this
  email: "john@example.com"
};

// Only include specific properties
const jsonString = JSON.stringify(user, ['name', 'email']);
console.log(jsonString);
// Output: {"name":"John","email":"john@example.com"}

Working with Fetch API

Fetching JSON from an API

// GET request
fetch('https://api.example.com/users')
  .then(response => response.json())  // Parse JSON automatically
  .then(data => {
    console.log(data);
  })
  .catch(error => console.error('Error:', error));

// Modern async/await syntax
async function getUsers() {
  try {
    const response = await fetch('https://api.example.com/users');
    const users = await response.json();
    console.log(users);
  } catch (error) {
    console.error('Error:', error);
  }
}

Sending JSON to an API

// POST request with JSON body
const newUser = {
  name: "Jane Doe",
  email: "jane@example.com"
};

fetch('https://api.example.com/users', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(newUser)
})
  .then(response => response.json())
  .then(data => console.log('Success:', data))
  .catch(error => console.error('Error:', error));

Working with LocalStorage

Storing Objects in LocalStorage

// Save object to localStorage
const userData = {
  name: "John",
  preferences: { theme: "dark", language: "en" }
};

localStorage.setItem('user', JSON.stringify(userData));

// Retrieve object from localStorage
const storedData = localStorage.getItem('user');
const user = JSON.parse(storedData);

console.log(user.preferences.theme);  // Output: dark

Advanced Techniques

Deep Cloning Objects

const original = {
  name: "John",
  address: { city: "New York", zip: "10001" }
};

// Create a deep clone
const clone = JSON.parse(JSON.stringify(original));

clone.address.city = "Boston";
console.log(original.address.city);  // Still "New York"

Custom toJSON Method

class User {
  constructor(name, password) {
    this.name = name;
    this.password = password;
  }

  // Custom serialization
  toJSON() {
    return {
      name: this.name,
      // Don't include password
    };
  }
}

const user = new User("John", "secret123");
console.log(JSON.stringify(user));
// Output: {"name":"John"}

Common Pitfalls

What Cannot Be Stringified

const obj = {
  fn: function() {},        // Functions are ignored
  undef: undefined,         // undefined is ignored
  date: new Date(),         // Converted to string
  regex: /test/,           // Converted to {}
  symbol: Symbol('test')   // Ignored
};

console.log(JSON.stringify(obj));
// Output: {"date":"2025-01-20T10:00:00.000Z","regex":{}}
Best Practice: Always validate and test your JSON data using our free JSON validator before using it in production!

Summary