JSON, short for JavaScript Object Notation, is a lightweight data interchange format. It's easy for humans to read and write, and simple for machines to parse and generate. JSON is language-independent but uses conventions familiar to programmers of the C-family of languages.
In JavaScript, JSON is used to serialize and transmit structured data over a network connection. It's commonly used to send data between a server and web application, serving as an alternative to XML.
JSON is built on two structures:
JSON supports the following data types:
Use JSON.parse()
to convert a JSON string into a JavaScript object:
const jsonString = '{"name": "John", "age": 30, "city": "New York"}';
const obj = JSON.parse(jsonString);
console.log(obj.name); // Output: John
Use JSON.stringify()
to convert a JavaScript object into a JSON string:
const obj = {name: "Jane", age: 25, city: "London"};
const jsonString = JSON.stringify(obj);
console.log(jsonString); // Output: {"name":"Jane","age":25,"city":"London"}
JSON is commonly used with AJAX to send and receive data from a server. This combination allows for dynamic, asynchronous updates to web pages without reloading the entire page.
While JSON syntax is similar to JavaScript object literal notation, there are some key differences:
JSON is a crucial part of modern web development, especially when working with APIs and data exchange. Understanding how to parse and stringify JSON in JavaScript is essential for any web developer. As you continue to explore JavaScript, consider learning about Fetch API and Promises to enhance your ability to work with JSON data in asynchronous contexts.