Working with JSON in TypeScript: Data Parsing and Serialization

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Introduction to Working with JSON in TypeScript



JSON (JavaScript Object Notation) remains one of the most popular formats for data exchange between client and server. In TypeScript, which is a strictly typed superset of JavaScript, working with JSON requires special attention to data types. In this article, we will thoroughly examine how to correctly parse and serialize JSON in TypeScript, avoiding typical errors and leveraging the benefits of static typing.



TypeScript provides all the built-in JavaScript methods for working with JSON but adds a powerful type system to them. This allows you to create more reliable and predictable code. We will cover both basic operations and advanced techniques, including custom validator functions and working with generics.



Basics of JSON Parsing: JSON.parse()



The JSON.parse() method converts a JSON string into a JavaScript object. In TypeScript, it is important to correctly type the result so that the compiler can verify the correctness of accesses to object properties.



Basic Syntax and Typing



Let's look at a simple example:



const jsonString = '{"name": "Anna", "age": 30, "city": "Moscow"}';const user = JSON.parse(jsonString);console.log(user.name); // Anna


The problem is that TypeScript does not know the structure of the user object. The variable has the type any, which deprives us of all the benefits of typing. The correct solution is to explicitly specify the type:



interface User {  name: string;  age: number;  city: string;}

const jsonString = '{"name": "Anna", "age": 30, "city": "Moscow"}';const user: User = JSON.parse(jsonString); // Error!// Type 'any' is not assignable to type 'User'.


TypeScript will throw an error because JSON.parse() returns any, and we are trying to assign it to a typed variable. Use type assertion:



const user = JSON.parse(jsonString) as User;console.log(user.name.toUpperCase()); // ANNA


Safe Parsing with Type Checking



The as type assertion is a quick solution, but it does not guarantee that the data actually matches the expected structure. For production code, it is recommended to create validator functions:



function parseUser(data: string): User | null {  try {    const parsed = JSON.parse(data);    if (typeof parsed === 'object' && parsed !== null &&        typeof parsed.name === 'string' &&        typeof parsed.age === 'number' &&        typeof parsed.city === 'string') {      return parsed as User;    }    return null;  } catch {    return null;  }}

const user = parseUser('{"name": "Ivan", "age": 25, "city": "SPb"}');if (user) { console.log(`User: ${user.name}, age: ${user.age}`);}


This approach prevents runtime errors if the server returns incorrect data.



Serialization: JSON.stringify()



The JSON.stringify() method converts a JavaScript object into a JSON string. In TypeScript, this method works the same as in JavaScript, but with type awareness.



Simple Serialization



const user: User = {  name: 'Maria',  age: 28,  city: 'Kazan'};

const jsonString = JSON.stringify(user);console.log(jsonString); // {"name":"Maria","age":28,"city":"Kazan"}


Formatting Parameters



For readable output, use the replacer and space parameters:



const user = {  name: 'Alexey',  age: 35,  city: 'Novosibirsk',  password: 'secret123'};

// Exclude the password fieldconst jsonString = JSON.stringify(user, ['name', 'age', 'city'], 2);console.log(jsonString);/* Output:{ "name": "Alexey", "age": 35, "city": "Novosibirsk"}*/


The repla

Blogs

Book Recommendations