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 often used when data is sent from a server to a web page.
JSON is a text format that is completely language independent but uses a format familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others.
Here’s how to use JSON in JavaScript:
1. Stringify a JavaScript Object
You can convert a JavaScript object into a JSON string using the JSON.stringify() method.
Example:
```
var person = {
name: “John”,
age: 31,
city: “New York“
};
var myJSON = JSON.stringify(person);
```
This will turn the JavaScript object into a string of text.
1. Parse JSON
If you receive data from a server in JSON format, you can convert it into a JavaScript object using the JSON.parse() method.
Example:
```
var json_data = ‘{name“John”, age, city“New York”}’;
var obj = JSON.parse(json_data);
```
Now, the data is a JavaScript object, so you can access values like you would do with any other JavaScript object:
```
var json_data = ‘{name“John”, age, city“New York”}’;
var obj = JSON.parse(json_data);
console.log(obj.name); // outputs “John“
```
JSON is a very commonly used tool when dealing with API and server communications. You often send data as JSON or receive data as JSON.
Remember, JSON is just a string of text and needs to be converted into an object to be used in JavaScript. You convert JSON into an object with the JSON.parse() method and convert an object into JSON with the JSON.stringify() method.