JSON (JavaScript Object Notation) is a popular data format used for transmitting and storing data. In JavaScript, we can use JSON to represent and work with objects and arrays.
JSON is a simple and easy-to-read data format, represented by key-value pairs. Data in JSON is described by basic data types such as number, string, object, array, boolean, and null. Here is an example of JSON format:
{
"name": "John",
"age": 25,
"city": "New York"
}
In the example above, we have three fields: name, age, and city. Each field is enclosed in double quotes "" and separated by a colon :. The fields are separated by a comma ,.
To convert from a JavaScript object to JSON, we can use the JSON.stringify() method.
var person = {
name: "John",
age: 25,
city: "New York"
};
var jsonPerson = JSON.stringify(person);
console.log(jsonPerson);
Result:
{"name":"John","age":25,"city":"New York"}
To convert from JSON to a JavaScript object, we can use the JSON.parse() method.
var jsonPerson = '{"name":"John","age":25,"city":"New York"}';
var person = JSON.parse(jsonPerson);
console.log(person.name);
console.log(person.age);
console.log(person.city);
Result:
John
25
New York