Objects in JSON are powerful ways of storing data. You can use JavaScript to create JSON objects. In this tutorial, you will learn different methodologies to create objects in JSON using JavaScript.
JSON Objects
JSON objects are formed using the curly braces which surrounds its data. These are written in a key-value pairing format. It is to be noted that the keys must have to be a string, and the value in the key-value pair must have to be anyone among the data types of JSON. Moreover, the key and value are separated by a colon (:) and where there are multiple key-value pairs, all of these are separated by a comma (,)
Creating JSON Objects
There are various ways of creating objects in JSON. The type depends on how you are creating and initializing the object. These are:
- Empty Object: You can also create empty JSON objects. For this, the syntax will be:
var obj1 = {};
- New Object: Moreover, you can also create new objects using this syntax:
var obj2 = new Object();
- An object with Attribute: Another way of creating objects is by assigning multiple attributes where the key will be the string, and the value can be either string or a numeric value. Let us take an example where a JSON file will store professor's data and their salaries.
var prof_details={ "name ": "Alex", "salary": 50000 };
Accessing Object Values
One way of accessing the values of JSON objects is by using the square bracket notation.
Example:
var objEmp={
"name": "Alex",
"salary": 50000,
"ta": null
};
travellingAllounce=objEmp[
"ta"
];
Looping Objects
JSON also allows developers to create objects within loops. But this takes the help of pure JavaScript to do that. Let us see how to do that:
Here is a simple code snippet showing the implementation of objects with loops.
var objEmp={
"name": "Alex",
"salary": 50000,
"ta": null
};
for(valinobjEmp){
document.getElementById("Value:").innerHTML+=val;
}
Nesting JSON Objects
It is also possible to write a JSON object within another object. This will look something like this:
var prof={
"name": "Alex",
"age": 24,
"subjects": {
"s1": "C++",
"s2": "software engineering",
"s3": "Data Science"
}
}
Deleting JSON Object
It is also possible to delete any properties of an object created within JSON using the delete keyword. The dot (.) or period operator needs to be used to access the nested object elements. The more you access the nested elements, the more you have to add dots. Let suppose you want to delete the subject1 from that previous JSON example so that you can use the delete keyword followed by this:
delete prof.subjects.s1;