JSON Array Literals in JavaScript
15 April 2025 | Category: JavaScript
A JSON array literal is a way to represent a list of values in JavaScript Object Notation (JSON) format.
â A JSON array is an ordered collection of values such as strings, numbers, booleans, objects, arrays, or
null
.
đ Example: JSON Array Literal
[
"HTML",
"CSS",
"JavaScript"
]
This array contains 3 strings. JSON arrays always use square brackets [ ]
and values are separated by commas.
â JSON Array of Objects
You can also store objects inside a JSON array:
[
{ "name": "Alice", "age": 25 },
{ "name": "Bob", "age": 30 },
{ "name": "Charlie", "age": 22 }
]
đĄ Use Case: Representing a Collection of Items
JSON arrays are perfect for storing:
- Lists of users
- Collections of products
- Multiple responses from a database
- Grouped data in APIs
đ§ JSON Array vs JavaScript Array
Feature | JSON Array | JavaScript Array |
---|---|---|
Format | Text-based (for storage) | Code-based (for logic) |
Quotes for strings | Must use double quotes | Can use single/double quotes |
Comments | â Not allowed | â Allowed |
Functions | â Not allowed | â Allowed |
đ ď¸ Working with JSON Arrays in JavaScript
đ¸ JSON String to JS Array
const jsonString = '["React", "Vue", "Angular"]';
const frameworks = JSON.parse(jsonString);
console.log(frameworks[0]); // Output: React
đ¸ JS Array to JSON String
const colors = ["red", "green", "blue"];
const jsonColors = JSON.stringify(colors);
console.log(jsonColors);
// Output: ["red","green","blue"]
â Data Types Allowed in JSON Arrays
Each item in a JSON array can be:
- A string â
"JavaScript"
- A number â
2025
- A boolean â
true
- Null â
null
- An object â
{ "name": "Alice" }
- Another array â
[1, 2, 3]
Example (Mixed types):
[
"Devin",
99,
true,
null,
{ "course": "Web Dev" },
[1, 2, 3]
]
â ď¸ JSON Array Rules
- Must begin and end with [ and ]
- Values are comma-separated
- Strings must use double quotes
- No functions or comments allowed
â Summary
Key Point | Description |
---|---|
Structure | Ordered list of values |
Use | Commonly used in APIs and data storage |
Compatibility | Easy to convert to/from JavaScript arrays |
Supported types | String, number, boolean, null, object, array |