JavaScript JSON Objects
JSON (JavaScript Object Notation) is a handy way to share data. It's easy for both people and computers to understand. In JavaScript, JSON helps organize data into simple objects. Let's explore how JSON works and why it's so useful for exchanging information.
const jsonData = {
"key1" : "value1",
...
};
const person = {
"name": "John",
"age": 30,
"city": "New York"
};
Explanation:
{ }
- Curly braces define the object."name"
,"age"
,"city" -
These are the keys (properties) of the object. Keys are always strings."John"
,30
,"New York" -
These are the corresponding values associated with each key.: -
Colon(:) separates keys and values., -
Comma(,) separates different key-value pairs within the object.
Accessing JSON Object Values
- The object values can be accessed by using the dot (".") notation.
- We can also access objects by using bracket([]) 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
Looping through JSON Object
Looping can be done in two ways:
- Looping of an object can be done by using a property for-in loop.
- For looping an object we can even use brackets ("[]") in the for-in loop property.
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
Converting a JSON Text to a JavaScript Object
To convert a JSON text to a JavaScript object, you can use the JSON.parse()
method.
const jsonString = '{"name": "GFG", "age": 30}';
const jsonObject = JSON.parse(jsonString);
console.log(jsonObject.name);
console.log(jsonObject.age);
Output
GFG 30
JavaScript JSON Objects -FAQ's
What is JSON and why is it used?
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. It is widely used for transmitting data between a server and web application as a text string.
How do you create a JSON object?
You create a JSON object by enclosing key-value pairs within curly braces
{}
, where keys are always strings and values can be any valid JSON data type (string, number, object, array, boolean, or null).
How do you access values in a JSON object?
You can access values in a JSON object using either dot notation (
jsonData.key
) or bracket notation (jsonData['key']
). Dot notation is used when you know the key beforehand, while bracket notation is useful when the key is dynamic or stored in a variable.