How to use eval() Function In Javascript

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

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() Method
  • Using eval() Function
  • Using new Function() Constructor

Similar Reads

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....

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....

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....