Introduction: Why JSON and TypeScript Are a Perfect Pair
JSON (JavaScript Object Notation) is a lightweight data interchange format that has become the de facto standard for web applications. TypeScript, in turn, adds static typing to JavaScript, making data handling safer and more predictable. For beginner developers, understanding how to parse (convert a string to an object) and serialize (convert an object to a string) JSON in TypeScript is a fundamental skill.
In this article, we will cover all aspects of working with JSON in TypeScript: from basic operations to advanced techniques with typing. You will learn how to avoid common mistakes and write clean, maintainable code.
Basics of JSON Parsing in TypeScript
JSON parsing is the process of converting a JSON-formatted string into a TypeScript object. The primary tool for this is the global function JSON.parse(). However, TypeScript has its own nuances related to typing.
Basic Parsing of a JSON String
Let's look at a simple example: we have a JSON string representing a user.
const jsonString = '{"name": "Anna", "age": 28, "isStudent": false}';const user = JSON.parse(jsonString);console.log(user.name); // "Anna"console.log(user.age); // 28The problem is that TypeScript does not know what structure the user object has. By default, JSON.parse() returns the any type, which negates the benefits of static typing.
Typing the Parsing Result
To fix this, we can explicitly specify the type of the return value. The simplest way is to use type assertion.
interface User { name: string; age: number; isStudent: boolean;}
const jsonString = '{"name": "Anna", "age": 28, "isStudent": false}';const user = JSON.parse(jsonString) as User;console.log(user.name); // TypeScript knows that name is a stringNow TypeScript understands the structure of the object and can check property types when accessing them.
Serializing Objects to JSON in TypeScript
Serialization is the reverse process: converting a TypeScript object into a JSON string. The function JSON.stringify() is used for this.
Basic Serialization Example
interface Product { id: number; title: string; price: number; inStock: boolean;}
const product: Product = { id: 101, title: "Laptop", price: 54999.99, inStock: true};
const jsonString = JSON.stringify(product);console.log(jsonString);// {"id":101,"title":"Laptop","price":54999.99,"inStock":true}The JSON.stringify() function automatically converts the object into a JSON string. It is important to remember that not all values can be serialized: functions, undefined, Symbol — they will be omitted or replaced with null.
Customizing Serialization with a Replacer
Sometimes you need to control which fields end up in the final string. For this, JSON.stringify() accepts a second argument — a replacer function or an array of keys.
const product = { id: 101, title: "Laptop", price: 54999.99, discount: 10, secretCode: "SECRET123"};
// Excluding secret dataconst safeJson = JSON.stringify(product, (key, value) => { if (key === 'secretCode') { return undefined; // Skip this field } return value;});console.log(safeJson);// {"id":101,"title":"Laptop","price":54999.99,"discount":10}Advanced Techniques: Working with Nested Objects and Arrays
In real-world applications, JSON is rarely flat. Nested objects, arrays, and complex data structures are common. TypeScript helps manage this complexity with interfaces.