JavaScript

JSON Arrays Explained

Every database in the world makes use of various data structures to manage and manipulate its data. Behind these databases are different programming languages that make up their structure. Arrays are a very prominent example of a data structure. JSON is a format through which various JavaScript-affiliated data is passed between the server and the website. Arrays are one of the data that can be sent and received between these two nodes.

In this article let us take a look at how JSON and the data stored within an array interact with each other.

JSON Array Datatypes
String
Number
Boolean
Object
Null
Array

JSON Array Structure

The structure of a JSON array is very similar to the structure of a JavaScript array. These are a few structural properties for a JSON array.

Declaration
To declare a JSON array, the “[ ]” brackets are used, with the items being stored inside the brackets. See the example below:

["item1"];

Indexes
Much like JavaScript, JSON arrays also utilize the index feature to access items within it starting from the first item whose index is 0. Below is an example of this:

jsonArray[0];

Adding multiple items
To add multiple items into the array, “, ” is used between the two items which will separate them from each other. Check out the example below:

["item1", "item2", "item3", "item4"];

Multiple datatypes
Different from many other languages, a single JSON array can contain elements of many different datatypes as shown below:

["item1", 5, true, "hi"];

JSON Document

Inside a JSON document, many different operations can be performed on the array. Take a look at the sample JSON document below:

{
    "name" : "Harris",
    "gender" : "M",
    "age" : 22,
    "hobbies" : [ "cricket", "painting", "gaming" ]
}

Get Value
To retrieve a value from a JSON array, follow this syntax and store into a variable:

value = sample.hobbies[2];

Delete Value
To perform deletion on any value in a JSON array, use the “delete” keyword as the sample below suggests:

delete sample.hobbies[2];

Update Value
To update any current value of the array, simply use the index number and assign it a new value as shown below:

sample.hobbies[1] = "boxing";

These are the most important properties of a JSON array. This article is a useful manual on how to use arrays inside JSON code.

Conclusion

JSON arrays are very similar to the arrays in JavaScript. They are declared the same way using square brackets and can contain multiple types of items within the same array. In this article, the majority of the crucial knowledge has been provided about the JSON arrays.

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.