How to Parse JSON in JavaScript
JSON.parse(): String to Object
JSON.parse() is JavaScript's built-in JSON parsing method, converting a JSON string into a JavaScript object (or array, primitive value). It's the foundational operation for handling API responses, reading JSON configurations, and similar tasks.
// ๅบๆฌ่งฃๆ / Basic parsing
const jsonStr = '{"name": "Alice", "age": 30}';
const obj = JSON.parse(jsonStr);
console.log(obj.name); // "Alice"
console.log(obj.age); // 30
// ่งฃๆๆฐ็ป / Parsing arrays
const arr = JSON.parse('[1, 2, 3]');
console.log(arr[0]); // 1
// ่งฃๆๅตๅฅ็ปๆ / Parsing nested structures
const nested = JSON.parse('{"user": {"name": "Bob", "scores": [95, 87]}}');
console.log(nested.user.scores[0]); // 95
JSON.stringify(): Object to String
JSON.stringify() is the inverse of JSON.parse(), converting a JavaScript value into a JSON string. The second argument is a replacer (to filter/transform fields); the third argument is the indent character count (for formatting):
const obj = { name: "Alice", age: 30, joined: new Date() };
// ๅบๆฌๅบๅๅ / Basic serialization
JSON.stringify(obj);
// '{"name":"Alice","age":30,"joined":"2025-01-01T00:00:00.000Z"}'
// ๆ ผๅผๅ่พๅบ๏ผ2็ฉบๆ ผ็ผฉ่ฟ๏ผ
JSON.stringify(obj, null, 2);
// ๅชๅ
ๅซ็นๅฎๅญๆฎต๏ผreplacer ไธบๆฐ็ป๏ผ
JSON.stringify(obj, ['name', 'age']);
// '{"name":"Alice","age":30}'
// ่ชๅฎไน่ฝฌๆข๏ผreplacer ไธบๅฝๆฐ๏ผ
JSON.stringify(obj, (key, value) => {
if (typeof value === 'number') return value * 2;
return value;
});
Error Handling: Catching JSON.parse Exceptions
JSON.parse() throws a SyntaxError when encountering invalid JSON โ must be handled with try-catch:
// ๅฎๅ
จ่งฃๆๅฝๆฐ / Safe parse function
function tryParseJSON(str) {
try {
return JSON.parse(str);
} catch (e) {
console.error('JSON parse error:', e.message);
return null;
}
}
// ๅธฆ้ป่ฎคๅผ็่งฃๆ / Parse with default value
function parseJSONWithDefault(str, defaultValue = {}) {
try {
return JSON.parse(str);
} catch {
return defaultValue;
}
}
JSON Handling in Fetch API
The modern browser Fetch API provides a response.json() method that automatically handles JSON parsing:
// GET ่ฏทๆฑ
async function getUser(id) {
const response = await fetch(`/api/users/${id}`);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json(); // ่ชๅจ่งฃๆ JSON
}
// POST ่ฏทๆฑๅ้ JSON
async function createUser(userData) {
const response = await fetch('/api/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(userData), // ๅบๅๅ่ฏทๆฑไฝ
});
return response.json();
}
JSON's Data Type Limitations in JavaScript
Some important things to note about JavaScript-to-JSON type mappings: Date objects: JSON.stringify() converts Date to ISO 8601 string (e.g., "2025-01-01T00:00:00.000Z"); JSON.parse() doesn't automatically restore it to a Date object โ manual conversion is needed. undefined: JSON has no undefined; JSON.stringify() ignores properties with undefined values. Functions: JSON doesn't support functions; they're ignored during serialization. NaN and Infinity: Serialized as null.
JSON Reviver: Custom Parse Logic
The second argument to JSON.parse() is a reviver function, allowing custom transformation of each key-value pair during parsing. Commonly used to automatically restore date strings to Date objects:
const dateRegex = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/;
function dateReviver(key, value) {
if (typeof value === 'string' && dateRegex.test(value)) {
return new Date(value);
}
return value;
}
const data = JSON.parse(jsonStr, dateReviver);
// ๆฅๆๅญๆฎต่ชๅจๅไธบ Date ๅฏน่ฑก
console.log(data.createdAt instanceof Date); // true
Handling Large Numbers: BigInt and Precision Issues
JavaScript's Number type can represent at most 15-16 significant decimal digits (Number.MAX_SAFE_INTEGER = 9007199254740991). Integers exceeding this range (common with backend-generated Snowflake IDs) lose precision during JSON.parse().
Solutions: have the backend return large integers as strings; or use a JSON library specifically handling large numbers (like json-bigint) that converts large numbers to BigInt type during parsing. This is an important detail to be aware of when integrating with certain backends (especially Java/.NET backends using 64-bit integer IDs).
Try the free tool now
Use Free Tool โ