JavaScript

Parse JSON in JavaScript

Learn how to parse JSON strings and objects in JavaScript with JSON.parse() and JSON.stringify() examples.

Try JSON Formatter →

Code Example

// Parse JSON string to object
const jsonString = '{"name": "John", "age": 30}';
const obj = JSON.parse(jsonString);
console.log(obj.name); // "John"

// Convert object to JSON string
const user = { name: "Jane", age: 25 };
const json = JSON.stringify(user);
console.log(json); // '{"name":"Jane","age":25}'

// Pretty print JSON
const pretty = JSON.stringify(user, null, 2);
console.log(pretty);
/*
{
  "name": "Jane",
  "age": 25
}
*/

// Handle parsing errors
try {
  const data = JSON.parse(invalidJson);
} catch (e) {
  console.error('Invalid JSON:', e.message);
}
Key Points: JavaScript provides built-in JSON.parse() for parsing JSON strings and JSON.stringify() for converting objects to JSON. Always wrap parsing in try-catch for error handling.

Related Examples

More JavaScript Examples