JavaScript

JSON Objects | Explained

Data does not always exist as individual values. In numerous cases, data needs to exist as a group. In situations like this, an idea like “objects” is utilized. An object is a collection of data related to the same class. For example, the object “person” will have various types of data and variables stored within it such as name, age, gender, etc.

In this article, an in-depth explanation will be given of the concept of objects within JSON code.

Properties of Object in JSON

These are some of the basic properties of an object in JSON.

Declaration
In JSON, an object is declared using the “{ }” brackets. Check out the example below:

var person = {}

Object Literal
Within an object, there can be several object literals. These literals are written in a “key: value” format. Refer to the example below:

var person = {
    "name" : "Harris"
}

In this example, the “name” string is the key and the corresponding data “Harris” is the value.

Multiple Object Literals
To add multiple object literals, commas can be used as shown in the example below:

var person = {
    "name" : "Harris",
    "age" : 22,
    "gender" : "M"
}

How to access Object values JSON?

To retrieve data from within an object, you need to use the “.” symbol to access objects as shown in the example below:

var sample = person.name;

The “.” in this code specifies the property of the object that we need to refer. See the snippet below for further clarification.

In using this method, not only can the value be accessed and displayed, but also assigned to variables.

How to Delete Object Values?

Deleting a value from within an object is very simple. We will utilize the “delete” keyword to perform the deletion functions. Its syntax is shown below:

delete person.name;

How to Update Object values?

To update any values inside an object the value first needs to be accessed and then a new value will be assigned. We have already learned above how values can be accessed. The code below applies this and updates the value:

person.name = "Anees";

In the sample snippet below we see how the value of the “name” attribute is being changed:

Conclusion

A JSON Object is a group of data that can contain a collection of keys and their values. It is declared using the curly braces and actions such as updating and deletion can be performed on its values after they are accessed using the “.” symbol. This article has equipped you with all the important

About the author

Shehroz Azam

A Javascript Developer & Linux enthusiast with 4 years of industrial experience and proven know-how to combine creative and usability viewpoints resulting in world-class web applications. I have experience working with Vue, React & Node.js & currently working on article writing and video creation.