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
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
JavaScript Date parse() Method
Next article icon

JavaScript JSON parse() Method

Last Updated : 21 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The JSON.parse() method is used to convert a JSON string into a JavaScript object. It’s become important when dealing with data in JSON format, interacting with APIs, or storing data in the browser.

  • It converts a JSON string into a JavaScript object.
  • Throws a SyntaxError if the input string is not valid JSON.
  • Accepts an optional reviver function to transform the parsed data.
JavaScript
const s = '{"name": "Rahul", "age": 25, "city": "Delhi"}'; const obj = JSON.parse(s); console.log(obj); 

Output
{ name: 'Rahul', age: 25, city: 'Delhi' } 
  • s is a valid JSON string.
  • JSON.parse() converts it into an object obj.
  • Now you can access the object’s properties like obj.name, obj.age, etc.

Syntax:

JSON.parse(text[, reviver]);
  • text: The JSON string to parse.
  • reviver (optional): A function to transform the parsed values before returning.

Using the Reviver Function

The reviver function allows you to modify the parsed values before they are returned. You can use it to manipulate data as needed during the parsing process.

JavaScript
const s = '{"name": "Rahul", "age": 25, "city": "Delhi"}'; const obj = JSON.parse(s, (key, value) => {     if (key === 'age') {         return value + 1;     }     return value; }); console.log(obj); 

Output
{ name: 'Rahul', age: 26, city: 'Delhi' } 
  • The reviver function adds 1 to the age value during the parsing process.
  • The modified object is returned with age updated to 26.

Common Use Cases of JSON.parse()

1. Parsing API Responses

When you receive a response from an API in JSON format, you need to convert the string to an object to work with it in JavaScript.

JavaScript
fetch('https://api.example.com/user')      // Fetches the data and converts it to JSON     .then(res => res.json())      .then(s => {          // Convert JSON string to object         const obj = JSON.parse(s);          // Access properties like obj.name         console.log(obj.name);       }); 

2. Storing and Retrieving Data from localStorage

You can store objects as JSON strings in localStorage. When you retrieve them, you need to parse the string back into an object.

JavaScript
// Saving an object const a = { name: 'Rahul', age: 25 }; localStorage.setItem('user', JSON.stringify(a));  // Retrieving and parsing the object const s = localStorage.getItem('user'); const obj = JSON.parse(s); console.log(obj.name);  // Output: Rahul 

3. Working with Configuration Files

You can load configuration settings stored in a JSON file, then parse it into a usable JavaScript object.

JavaScript
const s = '{"theme": "dark", "language": "en"}'; const obj = JSON.parse(s); console.log(obj.theme); 

Handling Common Errors with JSON.parse()

1. Invalid JSON Format: If the JSON string is malformed, JSON.parse() will throw a SyntaxError.

JavaScript
// Invalid JSON (keys must be in double quotes) const s = "{name: 'Rahul', age: 25}";   try {     const obj = JSON.parse(s);  // Throws SyntaxError } catch (e) {     console.log("Error:", e.message); } 

Output
Error: Unexpected token n in JSON at position 1 

2. Non-String Input: JSON.parse() only accepts strings. If you try to parse a number or an array, it will throw an error.

JavaScript
const a = 12345; try {     const obj = JSON.parse(a);   } catch (e) {     console.log("Error:", e.message);  } 


Next Article
JavaScript Date parse() Method

A

AkshayGulati
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • JavaScript-JSON

Similar Reads

  • JavaScript JSON Parser
    JSON (JavaScript Object Notation) is a popular lightweight data exchange format for sending data between a server and a client, or across various systems. JSON data is parsed and interpreted using a software component or library called a JSON parser. Through the JSON parsing process, a JSON string i
    3 min read
  • JavaScript Date parse() Method
    The JavaScript Date parse() method parses a date string and returns the number of milliseconds between the date string and midnight of January 1, 1970, UTC. If the argument is an invalid date string, it returns NaN (Not a Number). Syntax:Date.parse(datestring);Parameters:This method accepts a single
    3 min read
  • JavaScript JSON stringify() Method
    The JSON.stringify() method in JavaScript is used to convert JavaScript objects into a JSON string. This method takes a JavaScript object as input and returns a JSON-formatted string representing that object. Syntax: JSON.stringify(value, replacer, space);Parameters: value: It is the value that is t
    3 min read
  • Javascript | JSON PHP
    JSON stands for the JavaScript Object Notation. It is used to exchanging and storing the data from the web-server. JSON uses the object notation of JavaScript. JavaScript objects can be converted into the JSON and receive JSON format text into the JavaScript objects. Converting the JavaScript object
    7 min read
  • JavaScript JSON Objects
    JSON (JavaScript Object Notation) is a handy way to share data. It's easy for both people and computers to understand. In JavaScript, JSON helps organize data into simple objects. Let's explore how JSON works and why it's so useful for exchanging information. const jsonData = { "key1" : "value1", ..
    3 min read
  • JSON vs JavaScript Object
    JSON (JavaScript Object Notation) and JavaScript Objects are important for handling data in JavaScript, but they serve different purposes. JSON is a lightweight data format for transferring data, while JavaScript Objects are in-program data structures used for manipulation and logic. What is JSON?JS
    3 min read
  • JavaScript Number parseInt() Method
    TheparseInt method parses a value as a string and returns the first integer. It accepts a string argument and optional radix parameter, defining the numeral system base. This method is commonly used for converting string representations of numbers into integers. Example: The method takes two paramet
    2 min read
  • JavaScript JSONP
    What is JSONP?The **XMLHttpRequest (XHR)** is a tool used to retrieve data from a server. Once the data is received by the browser, it can be converted from a JSON string into a JavaScript object using the `JSON.parse()` method. However, XHR encounters an issue known as the **same-origin policy**. T
    4 min read
  • JavaScript Number parseFloat() Method
    JavaScript parseFloat() Method is used to accept the string and convert it into a floating-point number. If the string does not contain a numeral value or If the first character of the string is not a Number then it returns NaN i.e, not a number. It actually returns a floating-point number parsed up
    3 min read
  • How Does the JSON.parse() Method Works in JavaScript?
    The JSON.parse() method in JavaScript is used to convert a JSON string into a JavaScript object. This method is essential for working with JSON data, especially when fetching or processing data from APIs or external sources. Converts a JSON-formatted string into a JavaScript object.Maintains the str
    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