The Wayback Machine - https://web.archive.org/web/20241118222807/https://www.geeksforgeeks.org/how-to-parse-json-in-javascript/
Open In App

How to Parse JSON in JavaScript ?

Last Updated : 30 Apr, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Parse JSON in JavaScript, accepting a JSON string as input and returning a corresponding JavaScript object with two methods, using JSON.parse() for parsing JSON strings directly and employing the fetch API to parse JSON responses from web APIs. These techniques are crucial for seamless data manipulation and retrieval in your JavaScript projects.

Below are the methods to parse JSON in JavaScript:

Using JSON.parse() Method

In this approach, The JSON.parse() method is used to parse JSON strings into JavaScript objects. It's straightforward to use, accepting a JSON string as input and returning a corresponding JavaScript object. However, it's important to note its limitations, such as disallowing trailing commas and single quotes.

Example: The code below shows How to Parse JSON in JavaScript using JSON.parse() Method.

JavaScript
const jsonString = '{"name": "Geeks", "age": 30}';
const jsonObj = JSON.parse(jsonString);
console.log(jsonObj.name);
console.log(jsonObj.age);

Output
Geeks
30

Parsing JSON using fetch API

In this approach, fetching JSON data from web APIs, the fetch API returns responses in JSON format. Utilizing the JSON JSON () method of fetch, developers can seamlessly parse these responses into JavaScript objects.

Run the below command:

npm install node-fetch
node index.js

Updated Dependencies:

{
"type": "module",
"dependencies": {
"node-fetch": "^3.3.2"
}
}

Example: The code below shows How to Parse JSON in JavaScript using fetch API.

JavaScript
import fetch from 'node-fetch';

// The Random User Generator API provides a new set  
// of randomly generated user data with each request
fetch('https://api.randomuser.me/')
    
    // Handling the response asynchronously
    .then(response => response.json())
    
    // Processing the parsed JSON data
    .then(data => {
        console.log(data);
    })
    
    .catch(error => {
        console.error('Error fetching data:', error);
    });

Output:

{
results: [
{
gender: 'male',
name: [Object],
location: [Object],
email: 'ajinkya.rao@example.com',
login: [Object],
dob: [Object],
registered: [Object],
phone: '8621840038',
cell: '9145280882',
id: [Object],
picture: [Object],
nat: 'IN'
}
],
info: { seed: '209009bdf461ec82', results: 1, page: 1, version: '1.4' }
}

Previous Article
Next Article

Similar Reads

How to parse JSON object using JSON.stringify() in JavaScript ?
In this article, we will see how to parse a JSON object using the JSON.stringify function. The JSON.stringify() function is used for parsing JSON objects or converting them to strings, in both JavaScript and jQuery. We only need to pass the object as an argument to JSON.stringify() function. Syntax: JSON.stringify(object, replacer, space); Paramete
2 min read
What is difference between JSON.parse() and JSON.stringify() Methods in JavaScript ?
JSON.parse() converts JSON strings to JavaScript objects, while JSON.stringify() converts JavaScript objects to JSON strings. JavaScript utilizes JSON for data interchange between servers and web pages. These methods enable easy data manipulation and transport in web development. JSON.parse() MethodJSON.parse() converts a JSON string to a JavaScrip
2 min read
Why does Vite create multiple TypeScript config files: tsconfig.json, tsconfig.app.json and tsconfig.node.json?
In Vite TypeScript projects you may have noticed three typescript configuration files, tsconfig.json, tsconfig.app.json, and tsconfig.node.json. Each file is used for a different purpose and understanding their use cases can help you manage TypeScript configurations for your project. In this article, you will learn about the three TypeScript config
6 min read
JavaScript JSON parse() Method
The JSON.parse() method in JavaScript is used to parse a JSON string which is written in a JSON format and returns a JavaScript object. Syntax: JSON.parse( string, function ) Parameters: This method accepts two parameters as mentioned above and described below: string: It is a required parameter and it contains a string that is written in JSON form
2 min read
JavaScript SyntaxError - JSON.parse: bad parsing
This JavaScript exception thrown by JSON.parse() occurs if string passed as a parameter to the method is invalid. Message: SyntaxError: JSON.parse: unterminated string literal SyntaxError: JSON.parse: bad control character in string literal SyntaxError: JSON.parse: bad character in string literal SyntaxError: JSON.parse: bad Unicode escape SyntaxEr
2 min read
How does the JSON.parse() method works in JavaScript ?
The JSON.parse() method in JavaScript is used to parse a JSON (JavaScript Object Notation) string and convert it into a JavaScript object. JSON is a lightweight data-interchange format that is easy for humans to read and write, and it is also easy for machines to parse and generate. Example: Here, JSON.parse() take a JSON-formatted string (jsonStri
1 min read
How to Catch JSON Parse Error in JavaScript ?
JSON (JavaScript Object Notation) is a popular data interchange format used extensively in web development for transmitting data between a server and a client. When working with JSON data in JavaScript, it's common to parse JSON strings into JavaScript objects using the JSON.parse() method. However, parsing JSON data can sometimes lead to errors, e
1 min read
How to Parse JSON Data in JavaScript ?
JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write. It is easy for machines to parse and generate it. In JavaScript, parsing JSON data is a common task when dealing with APIs or exchanging data between the client and server. Table of Content Using JSON.parse() MethodUsing eval() Func
4 min read
How to universally parse JSON into blocks using jQuery ?
In jQuery, to parse any data to any block is carried over by using DOM Insertion methods. Some of DOM Insertion methods are append(), appendTo(), html(), prepend(), prependTo(), text(). To parse JSON into any block is also handled in same way but along with Ajax callback functions and parse.JSON() methods. Here parse.JSON() methods is deprecated in
3 min read
Moment.js Parse ASP.NET JSON Date
Moment.js is a date library for JavaScript that parses, validates, manipulates, and formats dates. We can use the moment() function passed with a string to parse dates in ASP.NET JSON format. The moment() function is used to create a moment using a string representing a date in ASP.NET JSON format. Syntax: moment( String ) Parameters: It takes a st
1 min read
How to Parse JSON using Node.js?
JSON stands for JavaScript Object Notation. The text-based data exchange format data exchange format allows you to transfer data between different languages and platforms. JavaScript is commonly used to interact with JSON files. JSON parsing is a common task when working with data from APIs, configuration files, or databases. In this article, we wi
2 min read
How to parse JSON string in Typescript?
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
4 min read
How to parse a JSON File in PHP?
We will explore how to parse a JSON file and display its data using PHP. PHP is a server-side scripting language commonly used to process and manipulate data. JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for both humans and machines to read and write. It stores data as name/value pairs. JSON Syntax Overvie
3 min read
How to parse JSON Data into React Table Component ?
In React parsing JSON Data into React Table Component is a common task to represent and structure data. We can render the JSON data into a table dynamically using the array map. Prerequisites:NPM & Node JSReact JSJSON parse()ApproachTo render JSON data in React Table we will be using the JavaScript array map method. Using the map function we wi
2 min read
Convert JSON String to Array of JSON Objects in JavaScript
Converting a JSON string to an array of JSON objects in JavaScript involves transforming a structured text format (JSON) into a usable JavaScript array. This allows developers to work directly with the data, enabling easier manipulation, analysis, and display of information. There are two approaches to solving this problem, which are discussed belo
2 min read
JSON Modify an Array Value of a JSON Object
The arrays in JSON (JavaScript Object Notation) are similar to arrays in JavaScript. Arrays in JSON can have values of the following types: nullbooleannumberstringarrayobject The arrays in JavaScript can have all these but it can also have other valid JavaScript expressions which are not allowed in JSON. The array value of a JSON object can be modi
2 min read
How to transforms JSON object to pretty-printed JSON using Angular Pipe ?
JSON stands for JavaScript Object Notation. It is a format for structuring data. This format is used by different web applications to communicate with each other. In this article, we will see How to use pipe to transform a JSON object to pretty-printed JSON using Angular Pipe. It meaning that it will take a JSON object string and return it pretty-p
3 min read
How to Write Postman Test to Compare the Response JSON against another JSON?
In the era of API-driven development, testing the API responses to ensure their correctness is of paramount importance. One such test includes comparing the JSON response of an API against a predefined JSON. In this article, we will delve into how to write a Postman test for this purpose. Table of Content What is Postman?JSON and its Role in APIsWh
4 min read
How to use cURL to Get JSON Data and Decode JSON Data in PHP ?
In this article, we are going to see how to use cURL to Get JSON data and Decode JSON data in PHP. cURL: It stands for Client URL.It is a command line tool for sending and getting files using URL syntax.cURL allows communicating with other servers using HTTP, FTP, Telnet, and more.Approach: We are going to fetch JSON data from one of free website,
2 min read
Difference between package.json and package-lock.json files
In Node, package.json file contains the list of dependencies and scripts in a project while the package.lock.json specifies their respective versions to ensure consistent installations in different environments. In this article, we will learn the major differences between package.json and package.lock.json and their needs in Node. Table of Content
4 min read
How to parse URL using JavaScript ?
Given an URL and the task is to parse that URL and retrieve all the related data using JavaScript. Example: URL: https://www.geeksforgeeks.org/courses When we parse the above URL then we can find hostname: geeksforgeeks.com path: /courses Method 1: In this method, we will use createElement() method to create a HTML element, anchor tag and then use
2 min read
How to parse a URL into hostname and path in javascript ?
We can parse a URL(Uniform Resource Locator) to access its component and this can be achieved using predefined properties in JavaScript. For Example, the first example parses the URL of the current web page and the second example parses a predefined URL. Example 1:This example parses the URL of the current web page. C/C++ Code <body style="
1 min read
How to parse HTTP Cookie header and return an object of all cookie name-value pairs in JavaScript ?
To parse HTTP Cookie header we will spilt the cookies data and create objects from the key-value extracted from cookies. Cookies are simply small text files that a web server sends to the user's browser. They contain the following data. Name-value pair with actual data.The expiry date for when the cookie becomes invalid.Domain and path of the serve
3 min read
How to Parse XML in JavaScript?
Parsing XML data is important because it allows JavaScript applications to extract structured information from XML documents. We will explore two different approaches to Parse XML in JavaScript. Below are the approaches to parsing XML in JavaScript: Table of Content Using DOM ParserUsing xml2js LibraryUsing DOM ParserIn this approach, we are using
2 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 parameter: datestring: This parameter holds the d
3 min read
How to Parse S-expressions in JavaScript?
The most simple and powerful notation used in Lisp programming is S-expressions and they are composed of atoms, say numbers or symbols or strings and lists (which too are S-expressions) parsing S-expressions in JavaScript can be done using a few basic techniques. What are S-expressions?To represent nested list data structures, we use s-expressions,
4 min read
How To Fetch And Parse RSS Feeds In JavaScript?
RSS (Really Simple Syndication) feeds are widely used for sharing updates from websites in a standardized XML format. By fetching and parsing RSS feeds, you can access the latest content from blogs, news sites, and other platforms. In this article, we’ll explore how to fetch and parse RSS feeds using JavaScript, using different methods. Table of Co
4 min read
How to Parse Float with Two Decimal Places in JavaScript?
JavaScript provides an inbuilt parseFloat() method to parse a string and returns a floating-point number. Below are the approaches to parse float to two decimal places in JavaScript: Table of Content Using parseFloat() MethodUsing Custom parseFloat Method Approach 1: Using parseFloat() MethodThe parseFloat() method converts a string to a floating-p
2 min read
Python | Parse a website with regex and urllib
Let's discuss the concept of parsing using python. In python we have lot of modules but for parsing we only need urllib and re i.e regular expression. By using both of these libraries we can fetch the data on web pages. Note that parsing of websites means that fetch the whole source code and that we want to search using a given url link, it will gi
2 min read
Node.js url.parse(urlString, parseQueryString, slashesDenoteHost) API
The url.parse() method takes a URL string, parses it, and it will return a URL object with each part of the address as properties. Syntax: url.parse( urlString, parseQueryString, slashesDenoteHost) Parameters: This method accepts three parameters as mentioned above and described below: urlString: It holds the URL string which needs to parse.parseQu
2 min read
three90RightbarBannerImg