English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

JSON Array

JSON arrays are similar to JavaScript arrays.

JSON arrays represent an ordered list of values. It can store strings, numbers, boolean values, or objects in a JSON array.

JSON object arrays

An array can be the value of an object property.

var myJSON = {
  "name":"Seagull",
  "age":22,
  "friends": ["Deadpool", "Hulk", "Thanos"]
}
Test and See ‹/›

Accessing array values

You can access array values by using the index of each element in the array.

var myJSON = {
  "name":"Seagull",
  "age":22,
  "friends": ["Deadpool", "Hulk", "Thanos"]
}
myJSON.friends[2]  // returns "Thanos"
Test and See ‹/›

Iterating over an array

Thefor-inLoops can be used to iterate over arrays.

var myJSON = {
  "name":"Seagull",
  "age":22,
  "friends": ["Deadpool", "Hulk", "Thanos"]
}
for (let x in myJSON.friends) {
document.getElementById("output").innerHTML += myJSON.friends[x];
}
Test and See ‹/›

Nested Arrays in JSON Objects

In nested arrays, another array can also be a value of an array.

var myJSON = {
  "name":"Seagull",
  "age":22,
  "friends": [
  {"heroName": "Deadpool", "skills": ["Martial artist", "Assassin"]},
  {"heroName": "Hulk", "skills": ["Superhuman Speed", "Superhuman Strength"]}, 
  {"heroName": "Thanos", "skills": ["Telepathy", "Superhuman senses"]}
  ] 
}
myJSON.friends[2].heroName;  // returns "Thanos"
Test and See ‹/›

nestedfor-inLoops can be used to access arrays within arrays.

for(let i in myJSON.friends) {
   x += "<h3>" + myJSON.friends[i].heroName + "</h3>";
   for(let j in myJSON.friends[i].skills) {
      x += myJSON.friends[i].skills[j] + "<br>";
   }
}
document.getElementById("output").innerHTML = x;
Test and See ‹/›

Modify Array Values

Index numbers can be used to modify values.

myJSON.friends[2] = "Ant-man";
Test and See ‹/›

Delete Array Items

You can use the delete keyword to remove values from an array.