1. Array Datatype in JSON
Similar to other programming languages, a JSON Array is a list of items surrounded in square brackets ([]). Each item in the array is separated by a comma.
- The array index begins with 0.
- The square brackets
[...]
are used to declare JSON array. - JSON array are ordered list of values.
- JSON arrays can be of multiple data types.
- JSON array can store
string
,number
,boolean
,object
or other array inside JSON array. - In JSON array, values must be separated by comma.
- Arrays in JSON are almost the same as arrays in JavaScript.
For example, given below is a JSON document that contains a JSON array of access rights.
{
"name" : "Admin",
"age" : 36,
"rights" : [ "admin", "editor", "contributor" ]
}
2. Array Operations
2.1. Get Value from Array
You can access the array values by using the index number:
x = myObj.rights[0];
Program output.
admin
2.2. Delete Array Value
Use the delete keyword to delete items from an array:
delete myObj.rights[1];
2.3. Update Array Value
Use the index number to modify an array:
myObj.rights[1] = "blogger";
2.4. Looping through Array Values
We can access array values by using a for-in loop:
for (i in myObj.rights)
{
x = myObj.rights[i];
console.log(x);
}
Program output.
admin
editor
contributor
3. Multi-dimensional Arrays
3.1. Creating a multi-dimensional array
We can store an array inside another JSON array. It is known as an array of arrays or a multi-dimensional JSON array.
var siteInfo = {
"name" : "blogger",
"users" : [
[ "admins", "1", "2" , "3"],
[ "editors", "4", "5" , "6"],
]
}
3.2. Iterating over multi-dimensional array
A simple for loop to iterate over a multi-dimensional array in JSON.
for (i in siteInfo .users)
{
for (j in siteInfo.users[i])
{
x = siteInfo.users[i][j];
console.log(x);
}
}
Program Output:
admins
1
2
3
editors
4
5
6
If I have multiple multi-dimentional array then how can I access it dynamically…If I take value from user and I want to match with JSON array and display all array values of array