Wednesday, July 3, 2024
HomeLanguagesJavascriptHow to transform JSON text to a JavaScript object ?

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

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

  • string: It is a required parameter and it contains a string that is written in JSON format.
  • function: It is an optional parameter and is used to transform results. The function called for each item.

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

Javascript




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.

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

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.

Javascript




// 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:

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

Nokonwaba Nkukhwana
Experience as a skilled Java developer and proven expertise in using tools and technical developments to drive improvements throughout a entire software development life cycle. I have extensive industry and full life cycle experience in a java based environment, along with exceptional analytical, design and problem solving capabilities combined with excellent communication skills and ability to work alongside teams to define and refine new functionality. Currently working in springboot projects(microservices). Considering the fact that change is good, I am always keen to new challenges and growth to sharpen my skills.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments