JAVASCRIPT

JavaScript JSON: Syntax, Usage, and Examples

JavaScript JSON (JavaScript Object Notation) is a lightweight data format used to store and exchange data. It is widely used in web applications, APIs, and databases due to its simple, readable structure that mirrors JavaScript objects. JSON provides a standardized way to transmit structured data between systems.


How to Use JavaScript JSON

JSON in JavaScript is primarily used for data serialization and deserialization. You can convert JavaScript objects to JSON strings and parse JSON strings back into JavaScript objects.

Defining a JSON Object in JavaScript

JSON objects follow a key-value structure enclosed in curly braces {}.

const person = {
  "name": "Alice",
  "age": 30,
  "city": "New York"
};
  • Keys must be enclosed in double quotes.
  • Values can be strings, numbers, booleans, arrays, or other JSON objects.

Converting a JavaScript Object to JSON

You can convert a JavaScript object to JSON using JSON.stringify().

const jsonString = JSON.stringify(person);
console.log(jsonString);
// Output: {"name":"Alice","age":30,"city":"New York"}

This process is called serialization, which is useful when sending data to a server.

Parsing JSON in JavaScript

To convert a JSON string back to a JavaScript object, use JSON.parse().

const jsonObject = JSON.parse(jsonString);
console.log(jsonObject.name); // Output: Alice

This process is called deserialization, allowing you to work with JSON data inside JavaScript.


When to Use JavaScript JSON

JSON is essential for handling structured data in JavaScript applications. Common use cases include:

  1. Exchanging data with APIs – Many web services return and accept JSON-formatted data.
  2. Storing configuration settings – JSON files store application settings in a human-readable format.
  3. Saving data in local storage – You can save JSON data in localStorage or sessionStorage in the browser.
  4. Database interactions – NoSQL databases like MongoDB store data as JSON-like documents.
  5. Logging and debugging – JSON provides a structured format for logging application data.

Examples of JavaScript JSON

How to Convert an Array to a JSON String in JavaScript

If you need to send an array as a JSON string, use JSON.stringify().

const fruits = ["apple", "banana", "cherry"];
const jsonFruits = JSON.stringify(fruits);
console.log(jsonFruits); // Output: ["apple","banana","cherry"]

Loop Through Values in an Array of JSON in JavaScript

When working with an array of JSON objects, you can loop through values using forEach().

const users = [
  { "name": "Alice", "age": 30 },
  { "name": "Bob", "age": 25 },
  { "name": "Charlie", "age": 35 }
];

users.forEach(user => console.log(user.name));
// Output:
// Alice
// Bob
// Charlie

JavaScript JSON Decode

If you receive a JSON-encoded string, use JSON.parse() to decode it.

const jsonString = '{"title": "JavaScript Basics", "author": "John Doe"}';
const book = JSON.parse(jsonString);
console.log(book.title); // Output: JavaScript Basics

Learn More About JavaScript JSON

JavaScript Object to JSON

You can convert an entire JavaScript object into JSON format using JSON.stringify().

const car = {
  brand: "Tesla",
  model: "Model S",
  electric: true
};

const jsonCar = JSON.stringify(car);
console.log(jsonCar);
// Output: {"brand":"Tesla","model":"Model S","electric":true}

JavaScript JSON Serialize JSON Object

Serialization means converting a JavaScript object into a JSON string so that it can be stored or transmitted.

const settings = {
  theme: "dark",
  notifications: true
};

const jsonSettings = JSON.stringify(settings);
localStorage.setItem("appSettings", jsonSettings);

This stores the JSON string in localStorage.

JavaScript Define JSON Object

In JavaScript, you can define a JSON object using the object literal syntax:

const jsonObject = {
  "username": "john_doe",
  "email": "john@example.com",
  "isActive": true
};

JavaScript JSON Stringify with Formatting

By default, JSON.stringify() returns a single-line string. You can format it using extra arguments for readability.

const formattedJson = JSON.stringify(jsonObject, null, 2);
console.log(formattedJson);

This formats the output with indentation.

JavaScript JSON Schema Library

A JSON schema defines the structure of JSON data. Libraries like Ajv help validate JSON against schemas.

const Ajv = require("ajv");
const ajv = new Ajv();

const schema = {
  type: "object",
  properties: {
    name: { type: "string" },
    age: { type: "number" }
  },
  required: ["name", "age"]
};

const validate = ajv.compile(schema);
const data = { name: "Alice", age: 30 };

console.log(validate(data)); // Output: true

Handling Errors in JSON Parsing

If you try to parse an invalid JSON string, JavaScript throws an error. Use try...catch to handle this safely.

const invalidJson = "{name: 'Alice', age: 30}"; // Invalid JSON

try {
  JSON.parse(invalidJson);
} catch (error) {
  console.error("Invalid JSON format:", error.message);
}

JavaScript JSON and AJAX

You can use fetch() to send and receive JSON data from a server.

fetch("https://jsonplaceholder.typicode.com/todos/1")
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error("Error fetching JSON:", error));

JavaScript JSON is a powerful tool for working with structured data. It allows you to serialize objects, parse JSON strings, and interact with APIs.

Learn to Code in JavaScript for Free
Start learning now
button icon
To advance beyond this tutorial and learn JavaScript by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

You can code, too.

© 2025 Mimo GmbH