Open In App

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.



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.

Syntax:

JSON.parse(string, function)

Parameters: This method accepts two parameters as mentioned above and described below

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




let obj = JSON.parse(
    '{"rollno":101, "name": "Nikita","age": 21}');
console.log("Roll no is " + obj.rollno );
console.log("Name is " + obj.name );
console.log("Age is " + obj.age );

Output
Roll no is 101
Name is Nikita
Age is 21

Approach 2: Using eval()

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.




// 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' }

Approach 3: Using Function constructor

The Function constructor converts JSON string to a JavaScript object by creating and invoking a function, but it’s unsafe and discouraged.

Syntax:

const jsonObj = new Function('return ' + jsonString)();

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




// JSON text
const jsonString =
    '{"name": "Rahul", "age": 30, "city": "Noida"}';
 
// Transform JSON text to a
//JavaScript object using Function constructor
const jsonObj = new Function('return ' + jsonString)();
 
console.log(jsonObj);

Output
{ name: 'Rahul', age: 30, city: 'Noida' }

References:


Article Tags :