Generating JSON in JavaScript
JSON.stringify() does the reverse of parsing — it converts a JavaScript object or array into a JSON-formatted text string, ready to send over a network or save to a file.
JSON.stringify()
Passing a JavaScript object to JSON.stringify() produces a compact JSON string. Optional second and third arguments let you filter which properties are included and add indentation for readability.
const user = { name: "Naledi", age: 24, password: "secret123" };
const jsonString = JSON.stringify(user);
console.log(jsonString); // {"name":"Naledi","age":24,"password":"secret123"}
const pretty = JSON.stringify(user, null, 2); // indented with 2 spaces
console.log(pretty);
const filtered = JSON.stringify(user, ["name", "age"]); // exclude password
console.log(filtered); // {"name":"Naledi","age":24}
Common Mistakes
- Forgetting that JSON.stringify() silently drops functions, undefined values, and Symbol properties from the output.
- Accidentally including sensitive fields (like a password) in stringified data sent to a client or logged somewhere insecure.
- Assuming JSON.stringify() preserves the exact key order guaranteed in all cases — while modern engines generally preserve insertion order for string keys, it's not something to rely on for critical logic.
- Not using the indentation argument when generating JSON meant to be human-readable, like a config file.
Professional Tip
Use the replacer array argument of JSON.stringify(), e.g. JSON.stringify(user, ["name", "age"]), to explicitly whitelist which fields get serialised — a simple, effective way to avoid accidentally leaking sensitive data.
Your Turn
Write a JavaScript object representing a user with a password field, then use JSON.stringify() with a replacer array to produce a JSON string that excludes the password.
Mini Quiz
What does JSON.stringify() do with a function property on an object?
JSON.stringify() simply skips function-valued properties (along with undefined and Symbol values) when serialising.