Arrays in JSON
- Arrays are used to represent a list of similar items in JSON.
- It is an ordered collection of values enclosed in square brackets separated by commas.
Syntax
{
"arrayName":[
"value1",
"value2",
"value3",
...
]
}
Example
{
"fruits":[
"apple",
"banana",
"orange",
"pear"
]
}
Output
The above example will produce the following output:
{
"fruits": [
"apple",
"banana",
"orange",
"pear"
]
}
Explanation
- An array is created by enclosing a list of values in square brackets separated by commas.
- Each value in the array is called an element.
- The elements of an array can be of any data type such as string, number, boolean, object or another array.
Use
Arrays are commonly used for representing a list of related objects or items such as:
- A list of students in a class
- A list of products in a shopping cart
- A list of employees in a company
Important Points
- Arrays are zero-indexed, i.e., the first element of an array has an index of 0, the second element has an index of 1 and so on.
- Arrays can be nested inside other arrays or objects.
- In JSON, arrays can contain objects.
Summary
- Arrays are used to represent a list of similar items in JSON.
- An array is an ordered collection of values enclosed in square brackets separated by commas.
- Each value in the array is called an element.
- Arrays can contain objects or other arrays and can be nested inside other arrays or objects.