JSON in Javascript
In JavaScript, JSON (short for 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. JSON is commonly used for exchanging data between a web server and a web application, or between different parts of a web application.
JSON data is represented as key-value pairs, similar to JavaScript objects, and it is designed to be language-agnostic, meaning that it can be used with any programming language that supports parsing JSON data.
The JSON
object in JavaScript provides methods to work with JSON data. Here are the methods and properties of the JSON
object:
- Methods:
JSON.parse()
: Parses a JSON string and returns a JavaScript object.JSON.stringify()
: Converts a JavaScript object into a JSON string.
- Properties:
JSON.version
: Returns the version of the JSON implementation in the browser.
Here is an example of using the JSON
methods:
const obj = {
name: 'John',
age: 30,
city: 'New York'
};
const jsonString = JSON.stringify(obj);
console.log(jsonString); // Output: {"name":"John","age":30,"city":"New York"}
const jsonObj = JSON.parse(jsonString);
console.log(jsonObj); // Output: { name: 'John', age: 30, city: 'New York' }
In this example, we first define a JavaScript object obj
. We then use the JSON.stringify()
method to convert the object to a JSON string, which we store in the jsonString
variable. Finally, we use the JSON.parse()
method to convert the JSON string back to a JavaScript object, which we store in the jsonObj
variable.