Open In App
Related Articles

Converting JSON text to JavaScript Object

Improve Article
Save Article
Like Article

Pre-requisite: JavaScript JSON 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 consist of curly braces ( { } ) at the either ends and have key-value pairs inside the braces. Each key-value pair inside braces are separated by comma (, ). JSON object looks something like this :


Example for a JSON object :


Conversion of JSON text to Javascript Object

JSON text/object can be converted into Javascript object using the function JSON.parse()


var object1 = JSON.parse('{"rollno":101, "name":"Mayank", "age":20}');

For getting the value of any key from a Javascript object, we can use the values as: object1.rollno If we pass a invalid JSON text to the function JSON.parse(), it will generate error (no output is displayed when using in tag of HTML). Examples : Here, in example, the JSON text ‘jsonobj’ have 3 key-value pair. Each of the pairs were able to be accessed by the Javascript object ‘obj’ using dot ( . ). ‘obj’ was a javascript object which was the result of the function JSON.parse().

var jsonobj = '{ "name":"Brendan Eich", "designerof":"Javascript", "bornin":"1961" }'; var obj = JSON.parse(jsonobj); print("JSON Object/Text : "); print( + ", who was born in " + obj.bornin + ", was the designer of " + obj.designerof); print("Use of Javascript object : "); print(jsonobj);


<h2>Converting JSON Text into Javascript Object</h2>
<b>JSON Object :</b>
<p id="demo"></p>
<b>Use of Javascript object :</b>
<p id="demo1"></p>
    var jsonobj ='{ "name":"Brendan Eich","designerof":"Javascript","bornin":"1961" }';
    // Here we convert JSON to object
    var obj = JSON.parse(jsonobj);
    document.getElementById("demo1").innerHTML =
               + ", who was born in "
                        + obj.bornin + ", was the designer of "
                        + obj.designerof;
    document.getElementById("demo").innerHTML =jsonobj;


Converting JSON text to JavaScript Object

Converting JSON text to JavaScript Object

Last Updated : 11 Jan, 2023
Like Article
Save Article
Similar Reads
Related Tutorials