Want to Master JSON & JavaScript?
Subscribe to Ram N Java for clear, beginner-friendly coding tutorials!
Subscribe on YouTubeWhat Are JSON Objects?
JSON objects are surrounded by curly braces { } and store data in key-value pairs. Keys must always be strings written inside double quotes, followed by a colon and the corresponding value.
Values inside a JSON object can be strings, numbers, booleans, arrays, null, or even another nested JSON object. Once you have a JSON object, retrieving its values in JavaScript is straightforward and flexible.
Two Ways to Retrieve Values from a JSON Object
-
Dot Notation: Access properties directly using a period followed by the property key name (e.g.,
myObj.name). This is the most common and readable method. -
Bracket Notation: Access properties by placing the key name as a string inside square brackets (e.g.,
myObj["name"]). This approach is especially useful when key names contain special characters, spaces, or dynamic variable names.
Practical Code Example
// 1. Define a JSON object
const myObj = { "name": "John", "age": 31, "city": "New York" };
// 2. Accessing a value using Dot Notation
const dotResult = myObj.name;
// 3. Accessing a value using Bracket Notation
const bracketResult = myObj["name"];
// 4. Output values
console.log(dotResult); // Outputs: John
console.log(bracketResult); // Outputs: John
Both techniques return the exact same value. Choose dot notation for clean, readable code and bracket notation whenever you need to look up keys dynamically.
No comments:
Post a Comment