J

JavaScript Handbook

Clean • Professional

JSON Objects & Arrays in JavaScript

2 minute

JSON Objects & Arrays

JSON (JavaScript Object Notation) is a text-based format for representing structured data. It is often used to exchange data between a web server and a client. Understanding JSON objects and arrays is fundamental for working with JSON effectively.

JSON Object Literals

A JSON object literal is a collection of key/value pairs enclosed in curly braces {}.

Example of a JSON string containing an object:

'{"name":"John", "age":30, "car":null}'

Inside the JSON string:

The actual object literal looks like this:

{"name":"John", "age":30, "car":null}

Rules for JSON object literals:

  • Keys must be strings wrapped in double quotes " ".
  • Values can be:
    • string
    • number
    • object
    • array
    • boolean
    • null
  • Key/value pairs are separated by commas.

Note: JSON is always a string format. When you convert it using JSON.parse(), it becomes a JavaScript object.

Converting JSON String to JavaScript Object

const myJSON = '{"name":"John", "age":30, "car":null}';
const myObj = JSON.parse(myJSON);

console.log(myObj.name); // John
console.log(myObj.age);  // 30

Accessing Properties

Dot notation:

console.log(myObj.name);

Bracket notation:

console.log(myObj["name"]);

Looping Through Properties

let text = "";
for (const key in myObj) {
  text += key + ": " + myObj[key] + ", ";
}
console.log(text); // name: John, age: 30, car: null,

JSON Array Literals

A JSON array is an ordered list of values enclosed in square brackets [].

Example of a JSON string containing an array:

'["Ford", "BMW", "Fiat"]'

Inside the JSON string:

The actual array literal looks like this:

["Ford", "BMW", "Fiat"]

Rules for JSON array values:

  • Must be a valid JSON data type:
    • string, number, object, array, boolean, null
  • Cannot include functions, undefined, or other JavaScript-specific types.

Converting JSON Array to JavaScript Array

const jsonArray = '["Ford", "BMW", "Fiat"]';
const cars = JSON.parse(jsonArray);

console.log(cars[0]); // Ford
console.log(cars.length); // 3

Accessing Array Values:

Arrays are accessed by their index:

console.log(cars[1]); // BMW

Objects Containing Arrays

JSON objects can contain arrays as values:

{
  "name": "John",
  "age": 30,
  "cars": ["Ford", "BMW", "Fiat"]
}

Accessing the Array Inside an Object:

const myJSON = '{"name":"John","age":30,"cars":["Ford","BMW","Fiat"]}';
const myObj = JSON.parse(myJSON);

console.log(myObj.cars[0]); // Ford
console.log(myObj.cars.length); // 3

Looping Through Arrays

Using a for loop:

for (let i = 0; i < myObj.cars.length; i++) {
  console.log(myObj.cars[i]);
}

Using a for-in loop:

for (let index in myObj.cars) {
  console.log(myObj.cars[index]);
}

Use for-of loop for cleaner syntax in modern JavaScript:

for (let car of myObj.cars) {
  console.log(car);
}

 

Article 0 of 0