Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to transform JSON text to a JavaScript object ?

  • Last Updated : 01 Dec, 2021

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

 

Conversion of JSON text to Javascript Object: JSON text/object can be converted into Javascript object using the function JSON.parse().

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:

HTML




<script>
    var obj = JSON.parse('{"rollno":101, 
        "name": "Nikita", "age": 21}');
    document.write("Roll no is " + obj.rollno + "<br>");
    document.write("Name is " + obj.name + "<br>");
    document.write("Age is " + obj.age + "<br>");
</script>

Output:

Roll no is 101
Name is Nikita
Age is 21

Example 2:

HTML




<html>
  
<body>
    <h2>JavaScript JSON parse() Method</h2>
    <p id="Geek"></p>
  
</body>
<script>
    var obj = JSON.parse('{"var1":"Hello","var2":"Geeks!"}');
    document.getElementById("Geek").innerHTML
        = obj.var1 + " " + obj.var2;
</script>
  
</html>

Output:

References:


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!