Introduction: Why JSON and TypeScript are the Perfect Pair
\nIn modern web development, JSON (JavaScript Object Notation) has become a universal format for exchanging data between client and server, storing configurations, and transmitting information in APIs. TypeScript, as a superset of JavaScript, adds a powerful type system to this flexibility, making working with JSON not only convenient but also safe. In this article, we will explore how to correctly parse (convert a JSON string into an object) and serialize (convert an object into a JSON string) data using TypeScript. The material is intended for beginner developers who are already familiar with the basics of TypeScript but want to work confidently with JSON.
\n\nWhat you will learn
\n- \n
- How to use the built-in methods
JSON.parse()andJSON.stringify(). \n - How to type data during parsing to prevent errors. \n
- How to handle exceptions and validate JSON correctness. \n
- Practical examples with real-world scenarios. \n
1. Basics: The JSON.parse() and JSON.stringify() Methods
\nTypeScript inherits two global methods for working with JSON from JavaScript. They are available without importing additional libraries.
\n\n1.1. Parsing JSON into an Object: JSON.parse()
\nThe JSON.parse() method takes a string in JSON format and returns a JavaScript object (or array, number, string). In TypeScript, we can specify the expected type of the result using generics.
// Simple example without typing\nconst jsonString = '{"name": "Alice", "age": 30}';\nconst user = JSON.parse(jsonString);\nconsole.log(user.name); // "Alice"\n\n1.2. Serializing an Object to JSON: JSON.stringify()
\nThe JSON.stringify() method converts a JavaScript object or value into a JSON string. It automatically handles all primitive types, arrays, and simple objects.
const user = {\n name: "Bob",\n age: 25,\n isAdmin: false\n};\nconst jsonString = JSON.stringify(user);\nconsole.log(jsonString); // '{"name":"Bob","age":25,"isAdmin":false}'\n\n2. Data Typing When Parsing JSON in TypeScript
\nThe main advantage of TypeScript is the ability to specify a type for the parsing result. This protects the code from errors at compile time and makes it self-documenting.
\n\n2.1. Using Interfaces and Generics
\nCreate an interface describing the structure of your data and pass it to JSON.parse() as a generic:
interface User {\n id: number;\n name: string;\n email: string;\n isActive: boolean;\n}\n\nconst jsonData = '{"id": 1, "name": "Victor", "email": "victor@example.com", "isActive": true}';\nconst user: User = JSON.parse(jsonData);\nconsole.log(user.email); // "victor@example.com"\n// user.id is now strictly number\n\n2.2. Handling Nested Objects and Arrays
\nInterfaces work well with complex structures:
\ninterface Address {\n city: string;\n zip: string;\n}\n\ninterface Employee {\n id: number;\n name: string;\n address: Address;\n skills: string[];\n}\n\nconst employeeJson = '{"id": 101, "name": "Elena", "address": {"city": "Moscow", "zip": "101000"}, "skills": ["TS", "JS", "Python"]}';\nconst employee: Employee = JSON.parse(employeeJson);\nconsole.log(employee.address.city); // "Moscow"\n\n2.3. What Happens if the Type Doesn't Match?
\nIt's important to understand: TypeScript only checks types at compile time. If at runtime a JSON with a different structure arrives (for example, age is a string instead of a number), an error will occur in the code, but not in JSON.parse(). For complete safety, use runtime validators (e.g., Zod or io-ts), but for most learning projects, interfaces are sufficient.
3. Serialization: Nuances and Custom Transformations
\nThe JSON.stringify() method can also be customiz