JSON Parse

Converting JSON strings to JavaScript objects

🔄 JSON.parse() Method

JSON.parse() converts a JSON string into a JavaScript object. This is essential when receiving JSON data from APIs or storage.


// JSON string
const jsonString = '{"name": "Alice", "age": 25}';

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

console.log(obj.name); // "Alice"
console.log(obj.age);  // 25
                                    

Output:

Alice

25

Parse Examples

📝

Simple Object

Parse basic JSON object

JSON.parse('{"key": "value"}')
📋

Array

Parse JSON array

JSON.parse('[1, 2, 3]')
🔢

Numbers

Parse numeric values

JSON.parse('42')

Booleans

Parse true/false values

JSON.parse('true')

🔹 Basic JSON.parse() Usage

Here are common parsing scenarios:

// Parse different JSON data types
const stringData = JSON.parse('"Hello World"');
console.log(stringData); // "Hello World"

const numberData = JSON.parse('42');
console.log(numberData); // 42

const booleanData = JSON.parse('true');
console.log(booleanData); // true

const nullData = JSON.parse('null');
console.log(nullData); // null

const arrayData = JSON.parse('[1, 2, 3, "hello"]');
console.log(arrayData); // [1, 2, 3, "hello"]

const objectData = JSON.parse('{"name": "Bob", "age": 30}');
console.log(objectData); // {name: "Bob", age: 30}

Output:

Hello World

42

true

null

[1, 2, 3, "hello"]

{name: "Bob", age: 30}

🔹 Parsing Complex JSON

Parse nested objects and arrays:

// Complex JSON string
const complexJson = `{
  "user": {
    "id": 123,
    "name": "Sarah Wilson",
    "email": "[email protected]",
    "preferences": {
      "theme": "dark",
      "notifications": true
    },
    "hobbies": ["reading", "photography", "hiking"]
  },
  "lastLogin": "2024-01-15T10:30:00Z"
}`;

// Parse the JSON
const userData = JSON.parse(complexJson);

// Access the data
console.log(userData.user.name);                    // "Sarah Wilson"
console.log(userData.user.preferences.theme);       // "dark"
console.log(userData.user.hobbies[0]);              // "reading"
console.log(userData.lastLogin);                    // "2024-01-15T10:30:00Z"

Output:

Sarah Wilson

dark

reading

2024-01-15T10:30:00Z

🔹 Error Handling

Always handle parsing errors with try-catch:

// Safe JSON parsing function
function safeJsonParse(jsonString) {
  try {
    const result = JSON.parse(jsonString);
    console.log("Parsing successful:", result);
    return result;
  } catch (error) {
    console.error("JSON parsing failed:", error.message);
    return null;
  }
}

// Valid JSON
safeJsonParse('{"name": "Alice"}');
// Output: Parsing successful: {name: "Alice"}

// Invalid JSON
safeJsonParse('{"name": Alice}'); // Missing quotes
// Output: JSON parsing failed: Unexpected token A in JSON at position 9

safeJsonParse('{name: "Alice"}'); // Missing quotes on key
// Output: JSON parsing failed: Unexpected token n in JSON at position 1

Common JSON Parsing Errors:

  • Missing quotes: Keys and strings must be in double quotes
  • Trailing commas: No comma after the last item
  • Single quotes: Use double quotes, not single
  • Undefined values: Use null instead of undefined

🔹 Real-World Examples

Common use cases for JSON.parse():

📡 API Response

// Simulating API response
const apiResponse = `{
  "status": "success",
  "data": {
    "products": [
      {"id": 1, "name": "Laptop", "price": 999.99},
      {"id": 2, "name": "Mouse", "price": 29.99}
    ]
  }
}`;

const response = JSON.parse(apiResponse);
response.data.products.forEach(product => {
  console.log(`${product.name}: $${product.price}`);
});
// Output: Laptop: $999.99
//         Mouse: $29.99

💾 Local Storage

// Retrieving data from localStorage
const savedSettings = localStorage.getItem('userSettings');

if (savedSettings) {
  const settings = JSON.parse(savedSettings);
  console.log("Theme:", settings.theme);
  console.log("Language:", settings.language);
} else {
  console.log("No saved settings found");
}

🔹 JSON.parse() with Reviver Function

Use a reviver function to transform values during parsing:

// JSON with date string
const jsonWithDate = '{"name": "Event", "date": "2024-01-15T10:30:00Z"}';

// Parse with reviver function to convert date strings to Date objects
const eventData = JSON.parse(jsonWithDate, (key, value) => {
  // Convert date strings to Date objects
  if (key === 'date') {
    return new Date(value);
  }
  return value;
});

console.log(eventData.name);                    // "Event"
console.log(eventData.date);                    // Date object
console.log(eventData.date.getFullYear());      // 2024

Output:

Event

Mon Jan 15 2024 10:30:00 GMT...

2024

🧠 Test Your Knowledge

What does JSON.parse() return when given a valid JSON string?