How to parse a JSON string in TypeScript

avatar
Borislav Hadzhiev

Last updated: Feb 27, 2024
3 min

banner

# Parse a JSON string in TypeScript

Use the JSON.parse() method to parse a JSON string in TypeScript.

The method parses a JSON string and returns the corresponding value. Make sure to explicitly type the result, which implicitly gets a type of any.

index.ts
const jsonStr = '{"id": 1, "name": "Bobby Hadz", "salary": 100}'; type Person = { id: number; name: string; salary: number; }; // ๐Ÿ‘‡๏ธ const result: Person const result: Person = JSON.parse(jsonStr); // ๐Ÿ‘‡๏ธ {id: 1, name: 'Bobby Hadz', salary: 100} console.log(result);

parse json string in typescript

The code for this article is available on GitHub

We used the JSON.parse method to parse a JSON string.

# Make sure to explicitly type the result

If you don't explicitly type the result, it gets assigned a type of any, which effectively turns off type-checking.

index.ts
const jsonStr = '{"id": 1, "name": "Bobby Hadz", "salary": 100}'; // โ›”๏ธ const result: any (BAD) const result = JSON.parse(jsonStr);

# Using a type assertion to type the result

You can also use a type assertion to set the type of the parsed value.

index.ts
const jsonStr = '{"id": 1, "name": "Bobby Hadz", "salary": 100}'; type Person = { id: number; name: string; salary: number; }; // ๐Ÿ‘‡๏ธ const result: Person const result = JSON.parse(jsonStr) as Person; // ๐Ÿ‘ˆ๏ธ type assertion

using type assertion to type the result

The code for this article is available on GitHub

# Typing an array correctly

If the value you are parsing is an array, type it as Type[], e.g. {id: number; name: string;}[].

index.js
const jsonStr = ` [ {"id": 1, "name": "Bobby Hadz", "salary": 100}, {"id": 2, "name": "Alice", "salary": 200} ]`; type Person = { id: number; name: string; salary: number; }; // ๐Ÿ‘‡๏ธ const result: Person const result = JSON.parse(jsonStr) as Person[]; console.log(result);

typing an array correctly

The code for this article is available on GitHub

I've also written an article on how to convert an object to a JSON string in TS.

# Mark properties that might not exist as optional

If you are unsure whether a specific property will exist on the object, mark it as optional.

index.ts
const jsonStr = '{"id": 1, "name": "Bobby Hadz", "salary": 100}'; type Person = { id: number; name?: string; // ๐Ÿ‘ˆ๏ธ optional property salary?: number; // ๐Ÿ‘ˆ๏ธ optional property }; // ๐Ÿ‘‡๏ธ const result: Person const result = JSON.parse(jsonStr) as Person; // result.name is string or undefined here if (typeof result.name === 'string') { // ๐Ÿ‘‡๏ธ result.name is string here console.log(result.name.toUpperCase()); // ๐Ÿ‘‰๏ธ "BOBBY HADZ" }
The code for this article is available on GitHub

We used a question mark to set the name and salary properties to optional.

If a property is set to optional, it can either be of the specified type or have an undefined value.

Since the name property could have a value of undefined, we can't directly call the toUpperCase() method because that could cause a runtime error.

In this case, you should use a type guard, to narrow down the type you're working with.

The if statement checks if result.name has a type of string.

We are able to use string-specific built-in methods in the if block because TypeScript knows that the value is a string.

There is no way for you to validate whether the type or interface you've defined matches the parsed JSON value at runtime.

This is because type aliases and interfaces don't exist at runtime. TypeScript only helps us catch bugs during development.

For this reason, you should try and be as accurate (strict) with your type definitions as necessary.

# Use a union if a property might have multiple types

For example, if a specific property might have multiple different types, use a union type.

index.ts
const jsonStr = '{"id": 1, "name": "Bobby Hadz", "salary": 100}'; type Person = { id: number; name: string; salary: number | null; // ๐Ÿ‘ˆ๏ธ number OR null }; // ๐Ÿ‘‡๏ธ const result: Person const result = JSON.parse(jsonStr) as Person; // ๐Ÿ‘‡๏ธ result.salary is a `number` or `null` here if (typeof result.salary === 'number') { // ๐Ÿ‘‡๏ธ result.salary is a number here // ๐Ÿ‘‡๏ธ "100.00" console.log(result.salary.toFixed(2)); }
The code for this article is available on GitHub

Union types are formed by combining two or more other types and represent values that may be any of the specified types.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev