Text-based open standard designed for human-readable data interchange.
JavaScript Object Notation, or JSON, 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 based on a subset of JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.
JSON syntax is derived from JavaScript object notation syntax, but the JSON format is text only. Code for reading and generating JSON data can be written in any programming language.
Here's a simple example of JSON data:
{ "name": "John", "age": 30, "city": "New York" }
In JSON, keys must be strings, written with double quotes, and values must be a valid JSON data type (string, number, object, array, boolean or null). Objects are enclosed in curly braces {}
and key-value pairs are separated by a colon :
. Arrays are enclosed in square brackets []
and values are separated by a comma ,
.
When receiving data from a web server, the data is always a string. To convert a JSON text into a JavaScript object, you can use the JSON.parse()
method. Here's an example:
let text = '{"name":"John", "age":30, "city":"New York"}'; let obj = JSON.parse(text); console.log(obj.name); // Outputs: John
If you have a JavaScript object and you want to convert it into a JSON string, you can use the JSON.stringify()
method. Here's an example:
let obj = {name: "John", age: 30, city: "New York"}; let json = JSON.stringify(obj); console.log(json); // Outputs: {"name":"John","age":30,"city":"New York"}
When you're working with APIs, you'll often receive data in JSON format. Here's an example of how you can fetch JSON data from an API and parse it:
fetch('https://api.example.com/data') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error));
In this example, response.json()
returns a promise that resolves with the result of parsing the body text as JSON, which can be used in the next then()
block.
Understanding how to work with JSON is crucial for any web developer, as it's the most common format for sending and receiving data from web APIs.