JavaScript Object Notation (JSON) is a lightweight, text-based, language-independent data interchange format. It is easy for humans to read and write and easy for machines to parse and generate. JSON is used to transmit data between a server and a web application, as an alternative to XML.
JSON is built on two structures:
1. A collection of key/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
2. An ordered list of values. In most programming languages, this is realized as an array, vector, list, or sequence.
The JSON format is simple and easy to understand. It is composed of key/value pairs, where the key is always a string enclosed in double quotes, and the value can be a string, number, object, array, boolean, or null.
For example:
```json
{
"name": "John Doe",
"age": 30,
"isStudent": false,
"books": [
"JavaScript: The Good Parts",
"Eloquent JavaScript"
],
"address": {
"street": "123 Main St",
"city": "Anytown"
},
"graduated": null
}
```
In this example, we have a JSON object with various key/value pairs. The name and age are string and number values, isStudent is a boolean, books is an array of strings, address is an object containing street and city, and graduated is null.
To use JSON in your JavaScript code, you can parse a JSON string using the `JSON.parse()` method, and you can stringify an object into a JSON string using the `JSON.stringify()` method.
Here's an example of parsing a JSON string into an object:
```javascript
const jsonString = '{"name":"John Doe","age":30,"isStudent":false,"books":["JavaScript: The Good Parts","Eloquent JavaScript"],"address":{"street":"123 Main St","city":"Anytown"},"graduated":null}';
const jsonObject = JSON.parse(jsonString);
console.log(jsonObject.name); // Output: John Doe
```
And here's an example of converting an object into a JSON string:
```javascript
const person = {
name: "John Doe",
age: 30,
isStudent: false,
books: ["JavaScript: The Good Parts","Eloquent JavaScript"],
address: {
street: "123 Main St",
city: "Anytown"
},
graduated: null
}
const jsonString = JSON.stringify(person);
console.log(jsonString);
// Output: {"name":"John Doe","age":30,"isStudent":false,"books":["JavaScript: The Good Parts","Eloquent JavaScript"],"address":{"street":"123 Main St","city":"Anytown"},"graduated":null}
```
JSON has become a popular data exchange format due to its simplicity and ease of use. It's widely used in web development for transferring data between a server and a web application. With this beginner's guide, you should now have a foundational understanding of JSON and how to work with it in your projects.