JavaScript JSON.parse()
The JSON.parse() method parses a JSON string and converts it into a JavaScript value (object, array, or primitive). It is the primary way to convert JSON text received from a server into usable JavaScript data.
Basic JSON.parse()
Pass a valid JSON string to JSON.parse() and it returns the corresponding JavaScript value.
// Parsing a JSON object
const jsonObj = '{"name": "Alice", "age": 30}';
const obj = JSON.parse(jsonObj);
console.log(obj.name);
console.log(obj.age);
console.log(typeof obj);
// Parsing a JSON number
const num = JSON.parse('42');
console.log(num);
console.log(typeof num);
// Parsing a JSON string
const str = JSON.parse('"hello"');
console.log(str);
// Parsing JSON boolean
const bool = JSON.parse('true');
console.log(bool);Parsing Arrays
JSON arrays are parsed into JavaScript arrays. The array elements can be any valid JSON type.
// Simple array
const numbers = JSON.parse('[1, 2, 3, 4, 5]');
console.log('Numbers: ' + numbers);
console.log('Length: ' + numbers.length);
console.log('First: ' + numbers[0]);
// Array of objects
const users = JSON.parse('[{"name": "Alice"}, {"name": "Bob"}]');
users.forEach(function(user) {
console.log('User: ' + user.name);
});
// Mixed types
const mixed = JSON.parse('[1, "two", true, null, ["nested"]]');
console.log('Mixed: ' + JSON.stringify(mixed));The Reviver Function
JSON.parse() accepts an optional second parameter called a reviver function. This function is called for each key-value pair and can transform the parsed values before they are returned.
const json = '{"name": "Alice", "score": "95", "bonus": "10"}';
// Reviver: convert numeric strings to numbers
const result = JSON.parse(json, function(key, value) {
if (key === 'score' || key === 'bonus') {
return Number(value);
}
return value;
});
console.log('Name: ' + result.name);
console.log('Score type: ' + typeof result.score);
console.log('Total: ' + (result.score + result.bonus));Parsing Dates
JSON does not have a Date type. Dates are typically stored as strings (ISO format). You can use the reviver function to convert date strings back into Date objects.
const json = '{"name": "Event", "date": "2024-06-15T10:30:00.000Z"}';
// Without reviver: date is a string
const raw = JSON.parse(json);
console.log('Date type: ' + typeof raw.date);
console.log('Date value: ' + raw.date);
// With reviver: convert to Date object
const withDates = JSON.parse(json, function(key, value) {
if (key === 'date') {
return new Date(value);
}
return value;
});
console.log('Date type: ' + typeof withDates.date);
console.log('Year: ' + withDates.date.getFullYear());
console.log('Month: ' + (withDates.date.getMonth() + 1));Nested Objects and Error Handling
JSON.parse() handles deeply nested objects. However, if the JSON string is invalid, it throws a SyntaxError. Always wrap JSON.parse() in a try/catch block when dealing with external data.
// Parsing nested objects
const nested = JSON.parse('{"user": {"name": "Alice", "address": {"city": "NYC"}}}');
console.log('City: ' + nested.user.address.city);
// Safe parsing function
function safeParse(jsonString) {
try {
return { data: JSON.parse(jsonString), error: null };
} catch (e) {
return { data: null, error: e.message };
}
}
// Valid JSON
const good = safeParse('{"valid": true}');
console.log('Valid: ' + JSON.stringify(good.data));
// Invalid JSON
const bad = safeParse('{invalid json}');
console.log('Error: ' + bad.error);
// Another invalid case
const bad2 = safeParse("{'single': 'quotes'}");
console.log('Error 2: ' + bad2.error);| Input | JSON.parse() Result | Type |
|---|---|---|
| {"a": 1} | { a: 1 } | object |
| [1, 2, 3] | [1, 2, 3] | array (object) |
| "hello" | hello | string |
| 42 | 42 | number |
| true | true | boolean |
| null | null | object |