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 a text-based format that is used to transmit data between a server and a web application, as an alternative to XML.
Although the syntax for JSON is based on JavaScript object notation, it is text-based, making it independent of any specific programming language. Additionally, because JSON is “self-describing,” it is straightforward to understand and work with. As such, JSON can be utilized in any programming language to read and generate data.
You can convert a JavaScript object or array to a JSON string using the JSON.stringify()
method.
const jsonString = JSON.stringify(myObj);
You can also convert a JSON string back to a JavaScript object or array using the JSON.parse()
method.
const myObj = JSON.parse(jsonString);
JavaScript JSON example
A simple example using JSON in JavaScript:
<!DOCTYPE html>
<html>
<body>
<script>
// JSON Object
const myObj = {
name: 'John',
age: 30,
hobbies: ['reading', 'traveling', 'coding'],
address: {
street: '123 Main St',
city: 'Anytown',
state: 'CA',
zip: '12345'
},
isStudent: true,
hasCar: null
};
// Convert the object to a JSON string
const jsonString = JSON.stringify(myObj);
// Log the JSON string
console.log(jsonString);
// Parse the JSON string back into an object
const parsedObj = JSON.parse(jsonString);
// Log the parsed object
console.log(parsedObj);
</script>
</body>
</html>
Output:
JSON syntax has a few simple and strict rules that must be followed:
- Data is represented as key-value pairs, with each pair separated by a comma.
- Keys must be strings and written in double quotes.
- Values must be valid JSON data types: string, number, object, array, boolean, or null.
- Strings are also written in double quotes.
- Numbers do not require quotes, but they cannot contain leading zeros, decimal points must be followed by at least one digit, and exponent notation is supported.
- Objects are enclosed in curly braces and contain key-value pairs.
- Arrays are enclosed in square brackets and contain values, separated by commas.
- Whitespace is allowed and ignored, except within strings.
Here’s an example of a valid JSON object that follows these rules:
{
"name": "John",
"age": 30,
"hobbies": ["reading", "traveling", "coding"],
"address": {
"street": "123 Main St",
"city": "Anytown",
"state": "CA",
"zip": "12345"
},
"isStudent": true,
"hasCar": null
}
It’s worth noting that JSON is a data interchange format, not a programming language. As a result, it lacks programming features such as control structures, variables, and functions. Its primary purpose is to facilitate the exchange of data between different systems.
Do comment if you have any doubts or suggestions on this JS JSON topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version