JSON is a text-based format that is language-independent, meaning that it can be used to exchange data between different programming languages. JSON stands for JavaScript Object Notation.
{ } //Empty JSON object
It is a lightweight data-interchange format that is easy for humans to read and write, and easy for machines to parse and generate.
{ string : value, .......}
JSON syntax is based on a subset of the JavaScript language syntax. Here are the basic rules for JSON syntax:
- Data is represented as key-value pairs, separated by a colon.
- Each key-value pair is separated by a comma.
- Data is enclosed in curly braces
{}
to represent an object. - String values are enclosed in double quotes
""
. - Numeric values are not enclosed in quotes.
- Boolean values are represented as either
true
orfalse
. - Null values are represented as the keyword
null
. - Arrays are represented as comma-separated lists of values enclosed in square brackets
JavaScript has a built-in function for converting JSON strings into JavaScript objects: JSON.parse()
JSON.parse()
And for converting aJSON: JSON.stringify()
JSON.stringify()
JSON JavaScript object notation example
Simple HTML example code has an object with several key-value pairs, including a nested object (address
) and an array of objects (phoneNumbers
). The keys are strings enclosed in double quotes, and the values can be strings, numbers, booleans, objects, or arrays.
<!DOCTYPE html>
<html>
<body>
<script >
var json_obj = {
"name": "John",
"age": 30,
"isStudent": true,
"grades": [85, 90, 92],
"address": {
"street": "123 Main St",
"city": "Anytown",
"state": "CA",
"zip": "12345"
},
"phoneNumbers": [
{
"type": "home",
"number": "555-1234"
},
{
"type": "work",
"number": "555-5678"
}
]
}
console.log(typeof(json_obj))
console.log(json_obj)
</script>
</body>
</html>
Output:
Do comment if you have any doubts or suggestions on this JS object notation topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version