How to transform JSON text into a JavaScript object?


In this article, we are going to explore a way to convert the JSON text into a JavaScript object. JSON, also known as JavaScript Object Notation, is a lightweight data-interchange format that is used for exchanging data over web browsers. JSON is derived from the JavaScript programming language but can be used by various other languages also including Python, Java, PHP, Ruby, etc. It is also language-dependent.

A JSON mainly follows a key-value data format that saves a value associated with a key. A JSON object consists of curly braces ({}) at both ends to define the starting and ending of a JSON object. Each key-value pair is segregated by a colon (:).

Example of a JSON Object −

{
   "name": "
   "designation": "
   "company": "
}

Conversion of a JSON object to JavaScript Object

A JSON object can be converted to a JavaScript object by using the JSON.p arse() method. This method takes in input for a JSON object and returns a JavaScript Object.

Syntax

JSON.parse(jsonString, function)

Parameters

  • jsonString − This contains the JSON string that is to be converted.

  • function − It is an optional parameter that is used for transforming the results.

Example 1

In the below example, we are going to convert a JSON text (string) to a JavaScript object and then display the same over on the HTML page.

# index.html

<!DOCTYPE html>
<html>
<head>
   <title>
      JSON to Javascript Object
   </title>
</head>
<body>
   <h2 style="color:red">
      Welcome To Tutorials Point
   </h2>
   <script>
      var obj = JSON.parse('{"name":"Steve","designation":"CEO","company":"Apple"}');
      document.write("Name is " + obj.name + "<br>");
      document.write("Designation is " + obj.designation + "<br>");
      document.write("Company is " + obj.company + "<br>");
   </script>
</body>
</html>

Output

The above program will produce the following output-

Example 2

# index.html

<!DOCTYPE html>
<html>
<head>
   <title>
      JSON to Javascript Object
   </title>
</head>
<body>
   <h2 style="color:red">
      Welcome To Tutorials Point
   </h2>
   <script>
      var transaction = JSON.parse('{"txnId":"12345","txnAmount":"100","balance":"50"}');
      console.log(transaction);
      console.log("Type of transaction is: " + typeof(transaction));
   </script>
</body>
</html>

Output

It will produce the following output in the Console.

{txnId: '12345', txnAmount: '100', balance: '50'}
balance: "50"
txnAmount: "100"
txnId: "12345"
[[Prototype]]: Object
Type of transaction is: object

Updated on: 28-Apr-2022

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements