Similar to other programming languages, an Array in JSON 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 array can store multiple value 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 is a JSON document which contains a JSON array rights
.
{ "name" : "Admin", "age" : 36, "rights" : [ "admin", "editor", "contributor" ] }
Get Value from Array
You can access the array values by using the index number:
x = myObj.rights[0];
Program output.
admin
Delete Array Value
Use the delete keyword to delete items from an array:
delete myObj.rights[1];
Update Array Value
Use the index number to modify an array:
myObj.rights[1] = "blogger";
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
Multi-dimensional array
We can store an array inside another JSON array. It is known as an array of arrays or multi-dimensional JSON array.
var siteInfo = { "name" : "blogger", "users" : [ [ "admins", "1", "2" , "3"], [ "editors", "4", "5" , "6"], ] }
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
Gauri says
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