Skip to content
LangStop

Tutorials

Keyboard Shortcuts

ActionShortcut
Toggle SidebarCtrl+B
Save TabCtrl+S
Close TabAlt+W
Switch to Tab 1Alt+Shift+1
Switch to Tab 2Alt+Shift+2
Switch to Tab 3Alt+Shift+3
Switch to Tab 4Alt+Shift+4
Switch to Tab 5Alt+Shift+5
Switch to Tab 6Alt+Shift+6
Switch to Tab 7Alt+Shift+7
Switch to Tab 8Alt+Shift+8
Switch to Tab 9Alt+Shift+9

How to Parse JSON in JavaScript — JSON.parse() Guide

What is JSON Parsing?

JSON parsing is the process of converting a JSON-formatted string into a usable JavaScript object. When you receive JSON data from an API, a file, or a web socket, it arrives as a string. Before you can access its properties, iterate over its elements, or manipulate its data, you must parse that string into a JavaScript data structure.

JavaScript provides the built-in JSON.parse() method for this purpose. It is part of the ECMAScript 5 specification and is available in all modern browsers and Node.js environments.


JSON.parse() Syntax

The JSON.parse() method accepts two arguments:

JSON.parse(text, reviver?)
Parameter Type Required Description
text string Yes The JSON string to parse. Must be valid JSON.
reviver function No A transformation function applied to each key/value pair before returning the result.

Returns: The parsed value (object, array, string, number, boolean, or null) corresponding to the JSON input.

Throws: A SyntaxError if the input string is not valid JSON.


Basic Example: Parsing a Simple JSON Object

The most straightforward use case is converting a JSON string into a JavaScript object:

const jsonString = '{"name": "Alice", "age": 30, "isDeveloper": true}';
const user = JSON.parse(jsonString);
 
console.log(user.name);        // "Alice"
console.log(user.age);         // 30
console.log(user.isDeveloper); // true
console.log(typeof user);      // "object"

The string '{"name": "Alice", "age": 30, "isDeveloper": true}' is valid JSON. After parsing, user becomes a regular JavaScript object with three properties. You can access them with dot notation or bracket notation just like any other object.


Parsing JSON Arrays

JSON arrays parse directly into JavaScript arrays:

const jsonArray = '["apple", "banana", "cherry"]';
const fruits = JSON.parse(jsonArray);
 
console.log(fruits);          // ["apple", "banana", "cherry"]
console.log(fruits[1]);       // "banana"
console.log(fruits.length);   // 3

Arrays of objects are common in API responses:

const jsonData = '[{"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"}]';
const users = JSON.parse(jsonData);
 
users.forEach(user => {
  console.log(`${user.id}: ${user.name}`);
});
// Output:
// 1: Alice
// 2: Bob

Parsing Nested JSON

JSON supports deeply nested structures, and JSON.parse() handles them naturally:

const nestedJson = `{
  "company": {
    "name": "TechCorp",
    "location": {
      "address": "123 Main St",
      "city": "San Francisco",
      "coordinates": {
        "lat": 37.7749,
        "lng": -122.4194
      }
    },
    "employees": [
      {"name": "Alice", "role": "Engineer"},
      {"name": "Bob", "role": "Designer"}
    ]
  }
}`;
 
const data = JSON.parse(nestedJson);
 
console.log(data.company.name);                    // "TechCorp"
console.log(data.company.location.city);           // "San Francisco"
console.log(data.company.location.coordinates.lat); // 37.7749
console.log(data.company.employees[0].name);       // "Alice"

Nested objects and arrays are fully preserved. You can traverse the parsed object using standard JavaScript property access and array methods.


Error Handling with try/catch

Parsing invalid JSON throws a SyntaxError. Always wrap JSON.parse() in a try/catch block when the input comes from an external source:

function safeParse(jsonString) {
  try {
    return { data: JSON.parse(jsonString), error: null };
  } catch (error) {
    return { data: null, error: error.message };
  }
}
 
// Valid JSON
const result1 = safeParse('{"name": "Alice"}');
console.log(result1.data.name); // "Alice"
 
// Invalid JSON
const result2 = safeParse('{name: "Alice"}'); // missing quotes around key
console.log(result2.error); // "Unexpected token n in JSON at position 1"
 
// Empty string
const result3 = safeParse('');
console.log(result3.error); // "Unexpected end of JSON input"
 
// Malformed array
const result4 = safeParse('[1, 2, 3,]'); // trailing comma
console.log(result4.error); // "Unexpected token ] in JSON at position 8"

A safe parsing wrapper is especially important when working with:

  • API responses — Network issues or server errors may return non-JSON payloads.
  • User input — Data entered into forms or text areas may not be valid JSON.
  • Local storage — Corrupted or manually edited stored data may break parsing.
  • File uploads — Uploaded JSON files may have encoding issues or syntax errors.

The Reviver Parameter

The second argument to JSON.parse() is a reviver function that transforms the parsed output. It runs for each key/value pair in the parsed object tree:

const jsonString = '{"name": "Alice", "birthDate": "1995-06-15"}';
 
const user = JSON.parse(jsonString, (key, value) => {
  if (key === "birthDate") {
    return new Date(value);
  }
  return value;
});
 
console.log(user.birthDate);                // Thu Jun 15 1995 (Date object)
console.log(user.birthDate.getFullYear());  // 1995
console.log(user.name);                     // "Alice" (unchanged)

Use Case: Converting Date Strings to Date Objects

APIs often return dates as ISO strings. The reviver can convert them automatically:

const apiResponse = `{
  "event": "Conference",
  "startDate": "2026-09-20T09:00:00.000Z",
  "endDate": "2026-09-22T18:00:00.000Z",
  "createdAt": "2026-01-15T12:00:00.000Z"
}`;
 
function dateReviver(key, value) {
  const datePattern = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/;
  if (typeof value === "string" && datePattern.test(value)) {
    return new Date(value);
  }
  return value;
}
 
const event = JSON.parse(apiResponse, dateReviver);
console.log(event.startDate.getHours()); // 9
console.log(event.endDate.getDate());    // 22

Use Case: Filtering or Mapping Values

The reviver can also filter or transform values:

const data = JSON.parse('[1, 2, 3, 4, 5]', (key, value) => {
  if (typeof value === "number") {
    return value * 2;
  }
  return value;
});
 
console.log(data); // [2, 4, 6, 8, 10]

Important: The reviver is called recursively. The this context is the current object being processed, and the key is an empty string "" for the top-level value. Avoid mutating the original object tree inside the reviver.


JSON.stringify() — The Reverse Operation

While JSON.parse() converts a string to an object, JSON.stringify() does the opposite — it converts a JavaScript object to a JSON string:

const user = {
  name: "Alice",
  age: 30,
  skills: ["JavaScript", "React", "Node.js"],
};
 
const jsonString = JSON.stringify(user);
console.log(jsonString);
// {"name":"Alice","age":30,"skills":["JavaScript","React","Node.js"]}

Pretty Printing with Space Parameter

const prettyJson = JSON.stringify(user, null, 2);
console.log(prettyJson);
// {
//   "name": "Alice",
//   "age": 30,
//   "skills": [
//     "JavaScript",
//     "React",
//     "Node.js"
//   ]
// }

The Replacer Parameter

Like the reviver in JSON.parse(), JSON.stringify() accepts a replacer function or array to control which properties are included:

const user = {
  name: "Alice",
  password: "secret123",
  email: "alice@example.com",
};
 
// Exclude sensitive fields
const safeJson = JSON.stringify(user, ["name", "email"]);
console.log(safeJson); // {"name":"Alice","email":"alice@example.com"}
 
// Or use a function
const filteredJson = JSON.stringify(user, (key, value) => {
  if (key === "password") return undefined;
  return value;
});
console.log(filteredJson); // {"name":"Alice","email":"alice@example.com"}

Common JSON Parsing Errors

Trailing Commas

JavaScript allows trailing commas in object literals, but JSON does not:

// INVALID JSON — will throw SyntaxError
const badJson = '{"name": "Alice", "age": 30,}';
JSON.parse(badJson); // SyntaxError: Unexpected token } in JSON at position 27

Fix: Remove trailing commas before parsing, or use a cleanup function:

function removeTrailingCommas(jsonString) {
  return jsonString.replace(/,([\s\n]*[}\]])/g, '$1');
}
 
const cleaned = removeTrailingCommas('{"name": "Alice", "age": 30,}');
const user = JSON.parse(cleaned);
console.log(user.name); // "Alice"

Single Quotes

JSON requires double quotes for keys and string values:

// INVALID JSON
JSON.parse("{'name': 'Alice'}"); // SyntaxError
JSON.parse('{"name": 'Alice'}'); // SyntaxError
 
// VALID JSON
JSON.parse('{"name": "Alice"}'); // OK

Fix: Use a helper to replace single quotes with double quotes (be careful not to affect apostrophes inside strings):

function normalizeQuotes(jsonString) {
  // Replace single-quoted keys with double-quoted keys
  return jsonString.replace(/(\s|,|\{)(\w+):/g, '$1"$2":');
}
 
const fixed = normalizeQuotes("{name: 'Alice'}");
// Result: '{"name": 'Alice'}' — still has single-quoted values

For a more robust solution, use the JSON Validator or JSON Fix tools.

Undefined and NaN Values

JavaScript values like undefined, NaN, and Infinity are not valid JSON:

JSON.stringify({ a: undefined }); // '{}' — undefined is omitted
JSON.stringify({ a: NaN });       // '{"a":null}' — NaN becomes null
JSON.stringify({ a: Infinity });  // '{"a":null}' — Infinity becomes null
 
// These cannot be parsed back to their original values
const parsed = JSON.parse('{"a": null}');
console.log(parsed.a); // null (not NaN or Infinity)

Unexpected Data Types

If you parse a JSON string and expect an object but receive a different type:

console.log(JSON.parse('"hello"'));      // "hello" (string)
console.log(JSON.parse('42'));           // 42 (number)
console.log(JSON.parse('true'));         // true (boolean)
console.log(JSON.parse('null'));         // null (null)

Always validate the parsed type before accessing properties:

function parseObject(jsonString) {
  try {
    const value = JSON.parse(jsonString);
    if (typeof value !== "object" || value === null || Array.isArray(value)) {
      return { data: null, error: "Expected a JSON object" };
    }
    return { data: value, error: null };
  } catch (e) {
    return { data: null, error: e.message };
  }
}

Performance Tips

1. Parse Once, Cache the Result

Avoid repeatedly parsing the same JSON string. Store the parsed object in a variable:

// BAD — parses on every access
function getUserName() {
  return JSON.parse(localStorage.getItem("user")).name;
}
 
// GOOD — parse once
let cachedUser = null;
function getUserName() {
  if (!cachedUser) {
    cachedUser = JSON.parse(localStorage.getItem("user"));
  }
  return cachedUser.name;
}

2. Use JSON.parse() Over eval()

Never use eval() to parse JSON. It is slow, insecure, and unnecessary. JSON.parse() is orders of magnitude faster and safely rejects invalid input.

3. Avoid Reviver Overhead When Unnecessary

If you do not need to transform values, omit the reviver parameter. Each function call adds overhead proportional to the object depth:

// Faster — no reviver
const data = JSON.parse(jsonString);
 
// Slower — reviver called for every key
const data = JSON.parse(jsonString, (key, value) => value);

4. Batch Parse Large Datasets

When processing large JSON arrays, consider streaming parsers for memory efficiency. The built-in JSON.parse() loads the entire object into memory. For very large datasets (100MB+), use libraries like stream-json or oboe.js for streaming:

// For extremely large JSON, consider streaming:
// npm install stream-json
 
const { parser } = require("stream-json");
const { streamValues } = require("stream-json/streamers/StreamValues");
const fs = require("fs");
 
fs.createReadStream("huge-data.json")
  .pipe(parser())
  .pipe(streamValues())
  .on("data", ({ value }) => {
    console.log("Record:", value);
  });

5. Use TextDecoder for Binary Data

If you are parsing JSON from a binary source (like a file buffer in Node.js), decode it first:

const decoder = new TextDecoder("utf-8");
const buffer = fs.readFileSync("data.json");
const jsonString = decoder.decode(buffer);
const data = JSON.parse(jsonString);

Parsing JSON from Different Sources

From Fetch API

async function fetchUser(userId) {
  try {
    const response = await fetch(`https://api.example.com/users/${userId}`);
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}`);
    }
    const user = await response.json(); // Built-in JSON parsing
    console.log(user.name);
    return user;
  } catch (error) {
    console.error("Failed to fetch user:", error);
    return null;
  }
}

The response.json() method internally calls JSON.parse() on the response body.

From Local Storage

// Save
const settings = { theme: "dark", fontSize: 14 };
localStorage.setItem("settings", JSON.stringify(settings));
 
// Load
const saved = localStorage.getItem("settings");
const parsed = saved ? JSON.parse(saved) : { theme: "light", fontSize: 12 };
console.log(parsed.theme); // "dark"

From a File (Browser)

function readJsonFile(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = (event) => {
      try {
        const data = JSON.parse(event.target.result);
        resolve(data);
      } catch (error) {
        reject(new Error("Invalid JSON file: " + error.message));
      }
    };
    reader.onerror = () => reject(new Error("Failed to read file"));
    reader.readAsText(file);
  });
}
 
// Usage with a file input
document.getElementById("fileInput").addEventListener("change", async (e) => {
  const file = e.target.files[0];
  try {
    const data = await readJsonFile(file);
    console.log("Parsed JSON:", data);
  } catch (error) {
    console.error(error.message);
  }
});

From a File (Node.js)

const fs = require("fs");
const path = require("path");
 
function loadJson(filePath) {
  try {
    const absolutePath = path.resolve(filePath);
    const content = fs.readFileSync(absolutePath, "utf-8");
    return JSON.parse(content);
  } catch (error) {
    if (error.code === "ENOENT") {
      console.error(`File not found: ${filePath}`);
    } else if (error instanceof SyntaxError) {
      console.error(`Invalid JSON in ${filePath}:`, error.message);
    } else {
      console.error("Unexpected error:", error.message);
    }
    return null;
  }
}
 
const config = loadJson("./config.json");
console.log(config?.appName);

JSON Data Type Mapping

When JSON.parse() converts JSON to JavaScript, types map as follows:

JSON Type JavaScript Type Example
string string "hello""hello"
number number 4242
boolean boolean truetrue
null null nullnull
object object {"a":1}{a:1}
array array [1,2][1,2]

Notable: JSON has no undefined, Date, Map, Set, BigInt, or typed array types. Attempting to JSON.stringify() these types may result in unexpected behavior.


LangStop JSON Tools

Related Tools

Try these complementary developer tools: