How to Format JSON in TypeScript
Feb 05, 20263 min read
TypeScript, being a superset of JavaScript, uses the native JSON.stringify() method to format JSON. Given its typed advantages, you can also assert schemas via Interfaces or Types before formatting.
Example Code
TypeScript
interface User {
name: string;
age: number;
city: string;
skills: string[];
}
const user: User = {
name: "John",
age: 30,
city: "New York",
skills: ["TypeScript", "React"]
};
// JSON.stringify takes 3 arguments: (value, replacer, space)
const formattedJson: string = JSON.stringify(user, null, 2);
console.log(formattedJson);Common Use Cases
- Formatting frontend request payloads for terminal debugging
- Displaying JSON in UI components
- Saving deeply structured typed configurations
💡 Pro Tips for TypeScript
- You can pass a string to the
spaceparameter instead of a number, for example"\t"to use tabs. - If your objects contain circular references,
JSON.stringifywill throw an error. Use a safe stringify library instead.
TypeScript-Ready Formatting
Need to create interfaces from JSON? Format your data first to visualize the structure, or use our specialized generator below.