Free Online Code Editor
Parse and stringify JSON data.
// JSON object
const jsonString = '{"name":"Alice","age":30,"city":"NYC"}';
// Parse JSON string to object
const obj = JSON.parse(jsonString);
console.log(obj.name); // "Alice"
console.log(obj.age); // 30
// Stringify object to JSON
const user = { name: "Bob", age: 25, active: true };
const jsonStr = JSON.stringify(user);
console.log(jsonStr);
// Pretty print
const pretty = JSON.stringify(user, null, 2);
console.log(pretty);
// Parse with reviver
const dateStr = '{"date":"2024-01-15T00:00:00Z"}';
const withDate = JSON.parse(dateStr, (key, value) => {
if (key === "date") return new Date(value);
return value;
});
console.log(withDate.date instanceof Date); // true
// Stringify with replacer
const sensitive = { name: "Alice", password: "secret123" };
const safe = JSON.stringify(sensitive, (key, value) => {
if (key === "password") return undefined;
return value;
});
console.log(safe);
// Handle arrays
const arr = [1, 2, 3];
const arrJson = JSON.stringify(arr);
console.log(JSON.parse(arrJson));
// Nested objects
const nested = {
user: { name: "Charlie", scores: [95, 87, 92] }
};
const nestedJson = JSON.stringify(nested);
const parsed = JSON.parse(nestedJson);
console.log(parsed.user.scores[0]); // 95
// Error handling
try {
const invalid = JSON.parse("{invalid json}");
} catch (error) {
console.error("Parse error:", error.message);
}
// Check if valid JSON
function isValidJSON(str) {
try {
JSON.parse(str);
return true;
} catch {
return false;
}
}
console.log(isValidJSON('{"valid":true}')); // true
console.log(isValidJSON('invalid')); // falseJSON.parse() converts string to object. JSON.stringify() converts object to string. Use replacer/reviver functions for custom handling. Always wrap parse in try/catch.