Example for a JSON object :
{
"rollno":101",
"name":"Mayank",
"age":20,
}
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(obj.name + “, who was born in ” + obj.bornin + “, was the designer of ” + obj.designerof);
print(“Use of Javascript object : “);
print(jsonobj);
Converting JSON Text into Javascript Object
JSON Object :
Use of Javascript object :
var jsonobj ='{ "name":"Brendan Eich","designerof":"Javascript","bornin":"1961" }';
// Here we convert JSON to object
var obj = JSON.parse(jsonobj);
document.getElementById("demo1").innerHTML =
obj.name + ", who was born in "
+ obj.bornin + ", was the designer of "
+ obj.designerof;
document.getElementById("demo").innerHTML =jsonobj;