Introduction
JSON (JavaScript Object Notation) is a lightweight data interchange format widely used in web development for transferring information between client and server. TypeScript, as a strictly typed superset of JavaScript, provides powerful tools for safe and convenient work with JSON. In this article, we will take a detailed look at how to perform JSON parsing and serialization in TypeScript, use types to ensure data correctness, and avoid common mistakes.
Proper work with JSON is critically important for creating reliable and scalable applications. TypeScript allows not only converting JSON strings to objects and back but also guaranteeing that the structure and data types match expectations. This is especially useful when working with APIs, configuration files, and databases.
Basics of JSON Parsing in TypeScript
JSON parsing is the process of converting a JSON string into a TypeScript object. The global method JSON.parse() is used for this. However, unlike JavaScript, in TypeScript we can specify the expected result type, which makes the code more predictable.
Simple Parsing Without Types
A basic example of parsing a JSON string:
const jsonString = '{"name": "Anna", "age": 30, "city": "Moscow"}';const user = JSON.parse(jsonString);console.log(user.name); // "Anna"In this case, TypeScript will infer the type any for the variable user, which reduces type safety. It is better to use explicit type specification.
Parsing with Type Specification via Interface
The most correct approach is to define an interface and use it during parsing:
interface User { name: string; age: number; city: string;}
const jsonString = '{"name": "Anna", "age": 30, "city": "Moscow"}';const user: User = JSON.parse(jsonString);console.log(user.name); // TypeScript knows this is a stringThis approach allows the IDE to provide autocompletion and check types at compile time.
Parsing Error Handling
JSON strings can be malformed, so it is important to handle exceptions:
function safeParseJSON<T>(json: string): T | null { try { return JSON.parse(json) as T; } catch (error) { console.error('JSON parsing error:', error); return null; }}
const invalidJson = '{"name": "Anna", age: 30}'; // Invalid JSONconst result = safeParseJSON<User>(invalidJson);if (result) { console.log(result.name);} else { console.log('Failed to parse JSON');}The safeParseJSON function accepts a generic parameter, allowing it to be reused for different data types.
Serializing Objects to JSON
Serialization is the reverse process of converting a TypeScript object into a JSON string. The method JSON.stringify() is used for this. TypeScript does not add new capabilities to this method but helps control which data ends up in the resulting string.
Basic Serialization
const user: User = { name: "Ivan", age: 25, city: "Saint Petersburg"};
const jsonString = JSON.stringify(user);console.log(jsonString); // {"name":"Ivan","age":25,"city":"Saint Petersburg"}Using a Replacer for Field Filtering
The second parameter of JSON.stringify() is a replacer function, which allows controlling which fields are included in the result:
const jsonStringFiltered = JSON.stringify(user, (key, value) => { if (key === 'age') { return undefined; // Exclude the age field } return value;});console.log(jsonStringFiltered); // {"name":"Ivan","city":"Saint Petersburg"}This is useful when you need to hide sensitive data or reduce the size of transmitted information.
Formatting with Space
Blogs
Book Recommendations
Read also
SOLID Principles in Go: Theory and Practice in Golang