JSON (JavaScript Object Notation) is a lightweight, text-based format used for storing and transporting data. It is often used when data is sent from a server to a webpage.
Example:
{
"name": "Wariz",
"age": 17,
"role": "Entrepreneur"
}
JSON is the universal way to exchange structured data between different programs or over the web. It serves as a "common language" that allows software written in different languages to communicate and share information.
JSON in JavaScript
While JSON is a text format, JavaScript provides built-in methods to easily switch between JSON strings and JavaScript objects.
1. JSON.parse()
This method is used to convert a JSON string into a JavaScript object. This is necessary when you receive data from a web server and want to access or manipulate it using object properties.
const jsonString = '{"name":"Wariz", "age":17}';
const userObject = JSON.parse(jsonString);
console.log(userObject.name); // "Wariz"
2. JSON.stringify()
This method is used to convert a JavaScript object into a JSON string. This is necessary when you need to send data to a web server or store it in a text-based format.
const user = { name: "Wariz", age: 17 };
const jsonString = JSON.stringify(user);
console.log(jsonString); // '{"name":"Wariz","age":17}'
Key Rules of JSON
To keep JSON "universal" and lightweight, it follows strict formatting rules:
- Data is in name/value pairs: Keys must be wrapped in double quotes (e.g.,
"name"). - Commas as separators: Items in an object or array are separated by commas. Trailing commas — a comma after the last item — are not allowed.
- Curly braces hold objects: Square brackets
[]hold arrays. - Double quotes only: You cannot use single quotes for strings or keys in JSON.