← Back to Blog

JavaScript JSON: Parse, Stringify, and Best Practices

Complete guide to JSON in JavaScript. Learn JSON.parse(), JSON.stringify(), error handling, and advanced techniques for web development.

Sarah Chen12 min readprogramming
S

Sarah Chen

Senior Software Engineer

Sarah is a full-stack software engineer with 8 years of experience in API development, TypeScript, and data engineering. She has designed and maintained large-scale JSON processing pipelines and contributes in-depth technical guides on performance optimisation, schema design, Python data workflows, and backend integration patterns.

TypeScriptAPI DevelopmentPythonData EngineeringJSON SchemaPerformance Tuning
12 min read

JSON in JavaScript

JavaScript has native JSON support through the JSON global object with two main methods: JSON.parse() and JSON.stringify().

JSON.parse() - Parse JSON Strings

Convert JSON string to JavaScript object:

const jsonString = '{"name": "Alice", "age": 30}';

const obj = JSON.parse(jsonString);

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

console.log(obj.age); // 30

Parsing Arrays

const arrayString = '[1, 2, 3, 4, 5]';

const numbers = JSON.parse(arrayString);

console.log(numbers[0]); // 1

JSON.stringify() - Convert to JSON

Convert JavaScript object to JSON string:

const user = {

name: "Bob",

age: 25,

active: true

};

const json = JSON.stringify(user);

console.log(json);

// {"name":"Bob","age":25,"active":true}

Pretty Printing

const formatted = JSON.stringify(user, null, 2);

console.log(formatted);

// {

// "name": "Bob",

// "age": 25,

// "active": true

// }

Replacer and Reviver Functions

Replacer - Filter Properties

const data = {

name: "Alice",

password: "secret",

age: 30

};

const json = JSON.stringify(data, (key, value) => {

if (key === "password") return undefined;

return value;

});

// {"name":"Alice","age":30}

Reviver - Transform Values

const json = '{"date":"2024-01-01T00:00:00Z"}';

const obj = JSON.parse(json, (key, value) => {

if (key === "date") return new Date(value);

return value;

});

Error Handling

Try-Catch for JSON.parse()

Always wrap JSON.parse() in try-catch when parsing untrusted input:

function safeJsonParse(jsonString) {

try {

return JSON.parse(jsonString);

} catch (error) {

console.error('Invalid JSON:', error.message);

return null;

}

}

const result = safeJsonParse('{"name": "Alice"}'); // Works

const invalid = safeJsonParse('{bad json}'); // Returns null, logs error

Detailed Error Messages

try {

const data = JSON.parse(invalidJson);

} catch (error) {

console.error("Invalid JSON:", error.message);

}

Working with Fetch API

// GET request

fetch('https://api.example.com/users')

.then(response => response.json())

.then(data => console.log(data));

// POST request

fetch('https://api.example.com/users', {

method: 'POST',

headers: { 'Content-Type': 'application/json' },

body: JSON.stringify({ name: 'Alice' })

});

LocalStorage with JSON

// Save

const user = { name: "Alice", age: 30 };

localStorage.setItem('user', JSON.stringify(user));

// Load

const stored = localStorage.getItem('user');

const user = JSON.parse(stored);

Common Pitfalls

Circular References

const obj = {};

obj.self = obj;

// ❌ Throws error

JSON.stringify(obj);

Undefined Values

JSON.stringify({ a: undefined, b: 2 });

// {"b":2} - undefined is omitted

Functions Are Ignored

JSON.stringify({ fn: () => {} });

// {} - functions are omitted

Best Practices

  • Always use try-catch with JSON.parse()
  • Validate JSON before parsing
  • Use replacer for sensitive data
  • Handle undefined/null appropriately
  • Be aware of data type limitations
  • Conclusion

    Master JSON.parse() and JSON.stringify() for all your JavaScript JSON needs. Remember to handle errors and understand the limitations!

    Share:

    Related Articles