How to parse JSON string in Typescript? - GeeksforGeeks (2024)

Last Updated : 26 Apr, 2024

Summarize

Comments

Improve

In this tutorial, we will learn how we can parse a JSON string in TypeScript. The main reason for learning about it is to learn how we can explicitly type the resulting string to a matching type. The JSON.parse() method will be used to parse the JSON string by passing the parsing string as a parameter to it.

Syntax:

JSON.parse(parsingString);

We can type the parsed string with an explicit type using the following methods:

Table of Content

  • Typing parsed string using the type alias
  • Typing parsed string using interfaces
  • Typing parsed array string
  • Typing parsed string using classes

Typing parsed string using the type alias

The type alias will be used to define a new type with a mixture of different typed properties and can be used to type the parsed string.

Example: The below example will show how you can explicitly type the parsed string using type alias.

JavaScript
const jsonStr1 = '{"name": "GeeksforGeeks", "desc": "A Computer Science Portal for Geeks"}';const jsonStr2 = '{"name": "Google", "desc": "Searching Platform", "workforce": 2000}';type parseType = { name: string, desc: string, workforce?: number,};const parsedStr1: parseType = JSON.parse(jsonStr1);const parsedStr2: parseType = JSON.parse(jsonStr2);console.log(`Company Name:  ${parsedStr1.name},  Description:  ${parsedStr1.desc}`);console.log(`Company Name:  ${parsedStr2.name},  Description: ${parsedStr2.desc},  Work Force: ${parsedStr2.workforce}`);

Output:

Company Name: GeeksforGeeks, Description: A Computer Science Portal for GeeksCompany Name: Google, Description: Searching Platform, Work Force: 2000

Typing parsed string using interfaces

The interfaces can also be used to type the parsed string to the required type as shown in the below example.

Example: This example shows the parsing of JSON string using interface.

JavaScript
const jsonStr1 = '{"name": "GeeksforGeeks", "desc": "A Computer Science Portal for Geeks"}';const jsonStr2 = '{"name": "Google", "desc": "Searching Platform", "workforce": 2000}';interface parseInterface { name: string; desc: string; workforce?: number;}const parsedStr1: parseInterface = JSON.parse(jsonStr1);const parsedStr2: parseInterface = JSON.parse(jsonStr2);console.log(`Company Name:  ${parsedStr1.name},  Description:  ${parsedStr1.desc}`);console.log(`Company Name:  ${parsedStr2.name},  Description: ${parsedStr2.desc},  Work Force: ${parsedStr2.workforce}`);

Output:

Company Name: GeeksforGeeks, Description: A Computer Science Portal for GeeksCompany Name: Google, Description: Searching Platform, Work Force: 2000

Typing parsed array string

An array string can also be parsed using the parse method and required to be typed as an explicit array of required types.

Syntax:

const parsedString = JSON.parse(string) as createdType[];

Example: The below example will explain how to type an parsed array string.

JavaScript
const jsonStr = `[ {"name": "GeeksforGeeks", "desc": "A Computer Science Portal for Geeks"}, {"name": "Google", "desc": "Searching Platform", "workforce": 2000}]`;type parsedType = { name: string, desc: string, workforce?: number}const parsedStr = JSON.parse(jsonStr) as parsedType[];console.log(`Company Name:  ${parsedStr[0].name},  Description:  ${parsedStr[0].desc}`);console.log(`Company Name:  ${parsedStr[1].name},  Description:  ${parsedStr[1].desc}`);

Output:

Company Name: GeeksforGeeks, Description: A Computer Science Portal for GeeksCompany Name: Google, Description: Searching Platform, Work Force: 2000

Typing parsed string using classes

Using classes is another effective way to parse JSON strings in TypeScript. We can define a class that represents the structure of the JSON data, providing type safety and better organization.

Example: Below is an example illustrating the parsing of a JSON string using a class-based approach.

JavaScript
class Company { name: string; desc: string; workforce?: number; constructor(name: string, desc: string, workforce?: number) { this.name = name; this.desc = desc; this.workforce = workforce; }}const jsonStr1 = '{"name": "GeeksforGeeks", "desc": "A Computer Science Portal for Geeks"}';const jsonStr2 = '{"name": "Google", "desc": "Searching Platform", "workforce": 2000}';const parsedStr1 = JSON.parse(jsonStr1);const parsedStr2 = JSON.parse(jsonStr2);const parsedCompany1: Company = new Company(parsedStr1.name, parsedStr1.desc);const parsedCompany2: Company = new Company(parsedStr2.name, parsedStr2.desc, parsedStr2.workforce);console.log(`Company Name:  ${parsedCompany1.name},  Description:  ${parsedCompany1.desc}`);console.log(`Company Name:  ${parsedCompany2.name},  Description: ${parsedCompany2.desc},  Work Force: ${parsedCompany2.workforce}`);

Output:

Company Name: 
GeeksforGeeks,
Description:
A Computer Science Portal for Geeks
Company Name:
Google,
Description: Searching Platform,
Work Force: 2000


How to parse JSON string in Typescript? - GeeksforGeeks (1)

Improve

Please Login to comment...

How to parse JSON string in Typescript? - GeeksforGeeks (2024)
Top Articles
Are CDs Good Protection for a Bear Market?
ETFs: The Best and Worst Performers over the Past 12 months | Canstar
Katie Pavlich Bikini Photos
Gamevault Agent
Hocus Pocus Showtimes Near Harkins Theatres Yuma Palms 14
Free Atm For Emerald Card Near Me
Craigslist Mexico Cancun
Hendersonville (Tennessee) – Travel guide at Wikivoyage
Doby's Funeral Home Obituaries
Vardis Olive Garden (Georgioupolis, Kreta) ✈️ inkl. Flug buchen
Select Truck Greensboro
Things To Do In Atlanta Tomorrow Night
Non Sequitur
How To Cut Eelgrass Grounded
Pac Man Deviantart
Alexander Funeral Home Gallatin Obituaries
Craigslist In Flagstaff
Shasta County Most Wanted 2022
Energy Healing Conference Utah
Testberichte zu E-Bikes & Fahrrädern von PROPHETE.
Aaa Saugus Ma Appointment
Geometry Review Quiz 5 Answer Key
Walgreens Alma School And Dynamite
Bible Gateway passage: Revelation 3 - New Living Translation
Yisd Home Access Center
Home
Shadbase Get Out Of Jail
Gina Wilson Angle Addition Postulate
Celina Powell Lil Meech Video: A Controversial Encounter Shakes Social Media - Video Reddit Trend
Walmart Pharmacy Near Me Open
A Christmas Horse - Alison Senxation
Ou Football Brainiacs
Access a Shared Resource | Computing for Arts + Sciences
Pixel Combat Unblocked
Cvs Sport Physicals
Mercedes W204 Belt Diagram
Rogold Extension
'Conan Exiles' 3.0 Guide: How To Unlock Spells And Sorcery
Teenbeautyfitness
Weekly Math Review Q4 3
Facebook Marketplace Marrero La
Nobodyhome.tv Reddit
Topos De Bolos Engraçados
Gregory (Five Nights at Freddy's)
Grand Valley State University Library Hours
Holzer Athena Portal
Hampton In And Suites Near Me
Stoughton Commuter Rail Schedule
Bedbathandbeyond Flemington Nj
Free Carnival-themed Google Slides & PowerPoint templates
Otter Bustr
Selly Medaline
Latest Posts
Article information

Author: Horacio Brakus JD

Last Updated:

Views: 6623

Rating: 4 / 5 (51 voted)

Reviews: 90% of readers found this page helpful

Author information

Name: Horacio Brakus JD

Birthday: 1999-08-21

Address: Apt. 524 43384 Minnie Prairie, South Edda, MA 62804

Phone: +5931039998219

Job: Sales Strategist

Hobby: Sculling, Kitesurfing, Orienteering, Painting, Computer programming, Creative writing, Scuba diving

Introduction: My name is Horacio Brakus JD, I am a lively, splendid, jolly, vivacious, vast, cheerful, agreeable person who loves writing and wants to share my knowledge and understanding with you.