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

How to Parse JSON Data in JavaScript ?

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

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.

Using JSON.parse() Method

This is the recommended and safest way to parse JSON data in JavaScript. The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string.

Syntax:

let jsonObject = JSON.parse(jsonString);

Example: Parsing the Person JSON data using the JSON parse() method.

JavaScript
let jsonString = '{"name": "ABC", "age": 30}';
let jsonObject = JSON.parse(jsonString);
console.log(jsonObject.name);
console.log(jsonObject.age);

Output
ABC
30

Using eval() Function

Although it is not recommended due to security concerns, you can use the eval() function to parse JSON data. However, this method executes the code passed to it, which can pose security risks if the JSON data is from an untrusted source.

Syntax:

let jsonObject = eval('(' + jsonString + ')');

Example: Parsing the Person JSON data using the eval() method.

JavaScript
let jsonString = '{"name": "ABC", "age": 30}';
let jsonObject = eval('(' + jsonString + ')');
console.log(jsonObject.name); 
console.log(jsonObject.age);

Output
ABC
30

Using new Function() Constructor

Similar to eval(), you can also use the new Function() constructor to parse JSON data. However, this method also executes the code passed to it, making it susceptible to security vulnerabilities.

Syntax:

let parseJson = new Function('return ' + jsonString + ';');
let jsonObject = parseJson();

Example: Parsing the Person JSON data using the new Function() method.

JavaScript
let jsonString = '{"name": "ABC", "age": 30}';
let parseJson = new Function('return ' + jsonString + ';');
let jsonObject = parseJson();
console.log(jsonObject.name);
console.log(jsonObject.age);

Output
ABC
30

Using a Custom JSON Parser

While the JSON.parse() method is the standard way to parse JSON in JavaScript, creating a custom JSON parser can be an interesting exercise to understand how JSON parsing works. This method can be beneficial in learning scenarios or when needing specific custom parsing behavior.

Example: The following example demonstrates how to implement a basic custom JSON parser for parsing JSON data.

JavaScript
const jsonString = '{"name": "Alice", "age": 30, "profession": "Engineer"}';

function customJSONParser(jsonString) {
  let index = 0;

  function parseValue() {
    skipWhitespace();
    if (jsonString[index] === '"') return parseString();
    if (jsonString[index] === '{') return parseObject();
    if (jsonString[index] === '[') return parseArray();
    return parsePrimitive();
  }

  function parseString() {
    index++; // skip the opening quote
    let result = '';
    while (index < jsonString.length && jsonString[index] !== '"') {
      result += jsonString[index++];
    }
    index++; // skip the closing quote
    return result;
  }

  function parseObject() {
    index++; // skip the opening brace
    const result = {};
    skipWhitespace();
    while (index < jsonString.length && jsonString[index] !== '}') {
      const key = parseString();
      skipWhitespace();
      index++; // skip the colon
      const value = parseValue();
      result[key] = value;
      skipWhitespace();
      if (jsonString[index] === ',') index++; // skip the comma
      skipWhitespace();
    }
    index++; // skip the closing brace
    return result;
  }

  function parseArray() {
    index++; // skip the opening bracket
    const result = [];
    skipWhitespace();
    while (index < jsonString.length && jsonString[index] !== ']') {
      result.push(parseValue());
      skipWhitespace();
      if (jsonString[index] === ',') index++; // skip the comma
      skipWhitespace();
    }
    index++; // skip the closing bracket
    return result;
  }

  function parsePrimitive() {
    let start = index;
    while (index < jsonString.length && /[\w.]/.test(jsonString[index])) {
      index++;
    }
    const primitive = jsonString.slice(start, index);
    if (primitive === 'null') return null;
    if (primitive === 'true') return true;
    if (primitive === 'false') return false;
    return parseFloat(primitive);
  }

  function skipWhitespace() {
    while (/\s/.test(jsonString[index])) index++;
  }

  return parseValue();
}

const jsonObject = customJSONParser(jsonString);
console.log(jsonObject);
// Output: { name: 'Alice', age: 30, profession: 'Engineer' }

Output
{ name: 'Alice', age: 30, profession: 'Engineer' }



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
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
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 in JavaScript ?
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. Be
2 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
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
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
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
Use of data files (CSV, JSON) in Postman for data-driven testing
It is a software testing method having all test input data stored or documented in a single CSV/JSON file and using a single test script for testing the API request with various input scenarios. It separates the test script logic from the test data. In Postman, we can perform this using variables and data files (CSV or JSON). Key Features of Data-D
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
three90RightbarBannerImg