Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • TypeScript Tutorial
  • TS Exercise
  • TS Interview Questions
  • TS Cheat Sheet
  • TS Array
  • TS String
  • TS Object
  • TS Operators
  • TS Projects
  • TS Union Types
  • TS Function
  • TS Class
  • TS Generic
Open In App
Next Article:
How to Convert an Object to a JSON String in Typescript ?
Next article icon

How to parse JSON string in Typescript?

Last Updated : 26 Apr, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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 Geeks Company 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 Geeks Company 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 Geeks Company 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

Next Article
How to Convert an Object to a JSON String in Typescript ?

A

abhish8rzd
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • TypeScript

Similar Reads

  • How to Convert String to JSON in TypeScript ?
    Converting a string to JSON is essential for working with data received from APIs, storing complex data structures, and serializing objects for transmission. Below are the approaches to converting string to JSON in TypeScript: Table of Content Convert String to JSON Using JSON.parse()Convert String
    6 min read
  • How to Remove Spaces from a String in TypeScript ?
    TypeScript offers various inbuilt functions to remove spaces from a string. These functions can be used to remove spaces between characters or entire words. Below, we explore different approaches to remove spaces from a string in TypeScript. Table of Content Using split() and join() methodsUsing rep
    4 min read
  • How to Convert Map to JSON in TypeScript ?
    In TypeScript, we can convert the Map to JSON by manipulating the key-value pairs of the Map into JSON-formatted string. We can use various approaches like JSON.stringify, fast-json-stringify, and json-stringify-safe Libraries for the conversion. Table of Content Using JSON.stringifyUsing fast-json-
    5 min read
  • How to Format Strings in TypeScript ?
    Formatting strings in TypeScript involves combining and structuring text to produce clear and readable output. This practice is essential for creating dynamic and user-friendly applications, as it allows developers to seamlessly integrate variables and expressions into strings, enhancing the overall
    3 min read
  • How to Convert an Object to a JSON String in Typescript ?
    In TypeScript, an object is a collection of related data and functionality. Objects are made up of properties and methods. Properties describe the object, methods describe what it can do. Table of Content Using JSON.stringify()Using json-stringify-safe libraryUsing a Custom Serialization FunctionUsi
    5 min read
  • How to Convert String to Number in TypeScript?
    In TypeScript, converting a string to a number is a common operation that can be accomplished using several different methods. Each method offers unique advantages and can be chosen based on the specific requirements of your application. Below are the approaches to convert string to number in TypeSc
    4 min read
  • How to Filter Keys of Type string[] in TypeScript ?
    In TypeScript, the filtering of keys of type string[] can be done by iterating over the data object, and applying the condition to the string if the key is a string. If the condition is satisfied, then an array of output results is created which consists of filtered keys of type string[]. The below
    3 min read
  • How to Require a Specific String in TypeScript Interface ?
    To require a specific string in the TypeScript interface, we have different approaches. In this article, we are going to learn how to require a specific string in the TypeScript interface. Below are the approaches used to require a specific string in the TypeScript interface: Table of Content Using
    2 min read
  • How to Specify Optional Properties in TypeScript?
    TypeScript is a powerful programming language that extends JavaScript by adding optional static typing and class-based object-oriented programming. One of the key features of TypeScript is the ability to specify optional properties in interfaces and classes, providing flexibility to our object types
    3 min read
  • How to implement Type narrowing in TypeScript?
    Type narrowing in TypeScript refers to refining the type of a variable within a conditional block based on runtime checks. This is achieved through techniques like typeof guards, instance checks, or property existence checks, enabling more precise typing and avoiding type errors in subsequent code e
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences