Open In App

JavaScript JSON Objects

JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write and easy for machines to parse and generate. In JavaScript, JSON is often used to represent data in the form of objects.

JSON object Syntax:

const jsonData = { 
"key1" : "value1",
...
};

JavaScript JSON Objects Examples

Example 1: Here, is an example of creating simple JSON Object.






const person = {
  "name": "John",
  "age": 30,
  "city": "New York"
};

Explanation:

2. Accessing JSON Object Values

Example: In the below program we are accessing the object using “.” notation.






let myOrder, i;
 
// Object is created with name myOrder
myOrder = {
    "name_of_the_product": "Earbuds",
    "cost": "799",
    "warranty": "1 year "
};
 
// Accessing for particular detail
// from object myOrder
i = myOrder.name_of_the_product;
 
// It prints the detail of name
// of the product
console.log(i);

Output
Earbuds

Explanation: The JavaScript code defines an object `myOrder` with properties like product name, cost, and warranty. It accesses the product name and assigns it to `i`. Finally, it logs the product name “Earbuds” to the console.

3. Looping through JSON Object

Looping can be done in two ways –

Example: In the below example we are accessing a looping object using bracket[] notation.




let myOrder, a;
 
myOrder = {
    "name_of_product": "earbuds",
    "cost": "799",
    "warranty": "1 year"
};
 
for (a in myOrder) {
 
    // Accessing object in looping
    // using bracket notation
    console.log(myOrder[a]);
}

Output
earbuds
799
1 year

Explanation: The code initializes an object `myOrder` with product details. It iterates over each property using a `for-in` loop. Within the loop, it accesses each property value using bracket notation and logs them to the console. This prints the values of “earbuds”, “799”, and “1 year”.

4. Converting a JSON Text to a JavaScript Object

To convert a JSON text to a JavaScript object, you can use the JSON.parse() method.

Example: This example converts the JSON to JavaSctipt Object.




const jsonString = '{"name": "John", "age": 30}';
const jsonObject = JSON.parse(jsonString);
console.log(jsonObject.name); // Output: John
console.log(jsonObject.age); // Output: 30

Output
John
30

Explanation:


Article Tags :