How to useeval() in Javascript

Using eval() to convert a JSON string to a JSON object, the eval() function takes the JSON string as input and treats it as JavaScript code. It executes the code, creating a JavaScript object from the JSON string.

Syntax:

eval(string)

Example: In this example, we are using the above-explained approach.

Javascript




// JSON text
const jsonString =
    '{"name": "Nikita", "age": 26, "city": "Noida"}';
 
// Transform JSON text to a JavaScript object using eval()
const jsonObj = eval('(' + jsonString + ')');
 
console.log(jsonObj);


Output

{ name: 'Nikita', age: 26, city: 'Noida' }

How to transform JSON text to a JavaScript object ?

JSON (JavaScript Object Notation) is a lightweight data-interchange format. As its name suggests, JSON is derived from the JavaScript programming language, but it’s available for use by many languages including Python, Ruby, PHP, and Java, and hence, it can be said as language-independent. For humans, it is easy to read and write and for machines, it is easy to parse and generate. It is very useful for storing and exchanging data.

A JSON object is a key-value data format that is typically rendered in curly braces. JSON object consists of curly braces ( { } ) at either end and has key-value pairs inside the braces. Each key-value pair inside braces are separated by a comma (, ). JSON object looks something like this :

{
"key":"value",
"key":"value",
"key":"value",
}

Example for a JSON object :

{
"rollno":101",
"name":"Nikita",
"age":21,
}

There are several methods that can be used to Conversion of JSON text to Javascript Objects.

  • Using jSON.parse() method
  • Using eval()
  • Using Function constructor

Similar Reads

Approach 1: Using 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....

Approach 2: Using eval()

...

Approach 3: Using Function constructor

Using eval() to convert a JSON string to a JSON object, the eval() function takes the JSON string as input and treats it as JavaScript code. It executes the code, creating a JavaScript object from the JSON string....