JSON (JavaScript Object Notation)
JSON (JavaScript Object Notation):
JSON (JavaScript Object Notation) is a powerful data representation format that is simple for both, programmer and machine.
It is especially applied for transferring data between a server and a web application in preference to XML
JSON Syntax:
JSON data is arranged in an object notation style that are used in JavaScript objects. JSON values are strings, numbers, objects, arrays, booleans and NULL.
{
"name": "John Doe",
"age": 30,
"isStudent": false,
"courses": ["Math", "History", "English"],
"address": {
"city": "New York",
"zipCode": "10001"
},
"isActive": null
}
- Objects are enclosed in curly braces {}.
- Key-value pairs are separated by commas.
- Strings are enclosed in double quotes.
- Arrays are ordered lists of values and are enclosed in square brackets [].
Working with JSON in JavaScript:
Parsing JSON:
You can convert a JSON string into a JavaScript object using JSON.parse().
const jsonString = '{"name": "John Doe", "age": 30, "isStudent": false}';
const parsedData = JSON.parse(jsonString);
console.log(parsedData.name); // Output: John Doe
console.log(parsedData.age); // Output: 30
console.log(parsedData.isStudent); // Output: false
In the example above, the try...catch block is used with async/await to handle errors in an asynchronous operation.
Stringifying JavaScript Object to JSON:
You can convert a JavaScript object into a JSON string using JSON.stringify().
const data = {
name: "Jane Doe",
age: 25,
isStudent: true
};
const jsonString = JSON.stringify(data);
console.log(jsonString);
// Output: {"name":"Jane Doe","age":25,"isStudent":true}
Dealing with Nested Objects and Arrays:
JSON can represent nested structures easily.
const jsonData = '{"name": "Alice", "grades": [90, 85, 92], "address": {"city": "Seattle", "zipCode": "98101"}}';
const parsedData = JSON.parse(jsonData);
console.log(parsedData.name); // Output: Alice
console.log(parsedData.grades[0]); // Output: 90
console.log(parsedData.address.city); // Output: Seattle
That was a brief introduction on how to work with JSON in JavaScript.
Let’s make some considerations: normally you use API to retrieve JSON data from the server and process it within your web application.