JSON Objects in JavaScript
JSON objects are JavaScript Object Notation (JSON) literals represented as string data. They provide a lightweight, language-independent format for exchanging structured data between systems and APIs. To work effectively with JSON in JavaScript, you need to know how to build, parse, and access JSON objects.
What is a JSON Object Literal?
A JSON object literal is a string that follows the syntax rules of JavaScript Object Notation:
- A JSON object is an unordered collection of key/value pairs.
- Objects are enclosed in curly braces { } to denote an object literal.
- Keys and values are separated by a : colon.
- All JSON object keys must be a string in double quotes.
- Each key within an object must be unique to avoid collisions.
- Values can be any of the six valid JSON data types.
- Each key/value pair is separated by a comma ,.
- Trailing commas after the last name-value pair are not allowed.
JSON Object Literal
{"id":1,"name":"Alice","active":true,"score":95.5}
A JSON object can have nested objects also:
Nested JSON Object
{ "person": {"id": 1, "name": "Alice"}, "address": {"street": "123 Main St", "city": "New York"}, "contact": {"email": "alice@example.com", "phone": "555-1234"} }
A JSON object can contain six types of values, each representing a valid JSON data type:
- string
- number
- object
- array
- boolean
- null
From JSON Literal to JavaScript Object
Once you parse a JSON literal with JSON.parse(), it becomes a JavaScript object, which you can further process or manipulate.
Parse JSON Literal
const jsonLiteral = '{"id":1,"name":"Alice","active":true}'; const jsObject = JSON.parse(jsonLiteral); console.log(jsObject.name); // Alice console.log(jsObject.active); // true
Difference Between JavaScript Objects and JSON Strings
While JavaScript objects and JSON strings may look similar, they serve different purposes and behave differently. Here's how they compare:
JavaScript Object
- A native JavaScript structure used directly in code.
- Keys can be written without quotes.
- No parsing is required to use the object.
- Best for logic operations and in-browser manipulation.
JavaScript Object Example
const jsObject = { title: "Learning JavaScript", author: "Alice", pages: 320, printInfo: function () { return `${this.title} by ${this.author}`; } };
JSON String
- A JSON string is plain text formatted using JSON syntax rules.
- All keys must be enclosed in double quotes.
- Requires JSON.parse() to convert to a JavaScript object.
- Ideal for API communication and local storage.
JSON String Example
const jsonString = '{"title":"Learning JavaScript","author":"Alice","pages":320}'; // Convert JSON string to JavaScript object const jsObject = JSON.parse(jsonString);
Array of JSON Objects
You can use JSON arrays to store multiple objects, making it easy to represent lists or tables of data.
Array of Objects
const users = [ { id: 1, name: "Alice" }, { id: 2, name: "Bob" }, { id: 3, name: "Carol" } ];
Accessing Object Values
After creating a JavaScript object or parsing a JSON string, you can access its values by the following methods:
Accessing Methods
- Dot notation: jsObject.name
- Bracket notation: jsObject["name"]
- Destructuring Assignment: const { a, b } = obj
Access with Dot Notation
console.log(jsObject.author); // "Alice" console.log(jsObject.pages); // 320
Access with Bracket Notation
console.log(jsObject["author"]); // "Alice" console.log(jsObject["pages"]); // 320
Accessing Object Values with Destructuring
Destructuring lets you extract values from JSON objects directly into variables with matching keys.
Destructuring Object Values
const languages = { js: "JavaScript", py: "Python", go: "Go" }; // Destructuring object properties const { js, py, go } = languages; console.log("js →", js); console.log("py →", py); console.log("go →", go);
Looping Through JSON Objects
Iterate over a JSON object to access and process each key-value pair:
- Use for...in to loop over keys.
- Use Object.keys(), Object.values(), or Object.entries() for controlled iteration.
Loop with for...in
const langData = '{"name":"Python","creator":"Guido van Rossum","firstReleased":"1991","popular":true,"type":"High-level","paradigm":"Multi-paradigm"}'; const langObj = JSON.parse(langData); document.getElementById('langTitle').textContent = langObj.name; let output = ''; // Loop using for...in for (let key in langObj) { if (key !== "name") { output += `<p><strong>${key}:</strong> ${langObj[key]}</p>`; } }
Loop with Object.keys()
const langData = '{"name":"Python","creator":"Guido van Rossum","firstReleased":"1991","popular":true,"type":"High-level","paradigm":"Multi-paradigm"}'; const langObj = JSON.parse(langData); document.getElementById('langTitle').textContent = langObj.name; let output = ''; // Loop Object.keys & forEach() Object.keys(langObj).forEach(key => { if (key !== 'name') { output += `<p><strong>${key}:</strong> ${langObj[key]}</p>`; } });
Loop with Object.entries()
const langData = '{"name":"PHP","creator":"Rasmus Lerdorf","firstReleased":"1995","popular":true,"type":"Scripting","paradigm":"Imperative and object-oriented"}'; const langObj = JSON.parse(langData); document.getElementById('langTitle').textContent = langObj.name; let output = ''; // Loop Object.entries & forEach() Object.entries(langObj).forEach(([key, value]) => { if (key !== 'name') { output += `<p><strong>${key}:</strong> ${value}</p>`; } });
Caution:
Parsing JSON Strings to JavaScript Objects
Use JSON.parse() function to convert a JSON string into a JavaScript object:
Parse JSON String
const userData = '{"user":"Bob","age":25,"admin":false}'; const obj = JSON.parse(userData); document.getElementById('name').textContent = obj.user; document.getElementById('age').textContent = obj.age; document.getElementById('admin').textContent = obj.admin ? "Yes" : "No";
- Parses userData into a JS object
- Access properties using dot or bracket notation
Stringifying JavaScript Objects to JSON
Use JSON.stringify() function to serialize or convert a JavaScript object into a JSON string:
Stringify JavaScript Object
// Serialize a simple object const user = { name: "Alice", age: 30, isAdmin: false }; const jsonString = JSON.stringify(user);
- Converts user into a JSON string
- Useful for sending data via APIs or storing in localStorage