JSON - stands for Javascript object notation. It is used to store and transmit data between server and client.
Please keep in mind that JSON data are in key/value pairs that are separated by a comma.
JSON is derived from Javascript, therefore, JSON syntax and Javascript object literal syntax look like same but both have a little bit different.
JSON data consists of key/value
pairs. Key and value are separated by a comma. The key always exists left side while the value lies on the right side.
Keys are always kept within double quotes while value can be put either in the double quote(for string) or without double quote(in case of number).
"key":"value"
"city":"salempur"
In this example, "city" is the key while the value is "Salempur". value is put inside a double quote due to string.
The JSON object is written inside a curly bracket {}. It contains multi-key/value pairs. Each key-value pair is separated by a comma.
Let us understand it with the help of an example
{ "name": "Smith", "email": "work45@@gmail.com" }
It is of two types.
A JSON array is written inside a square bracket []. Let us understand it step by step with the help of an example.
It only contains string values. Let us see its example.
["mango","banana","orange","grape"]
Let us see an example of an array of strings.
[1, 4, 6, 3, 100]
Let us see it with the help of an example.
[true,false, false, true, true]
Every object is separated by a comma. Let us see its example.
[
{ "name": "Smith", "age": 22 },
{ "name": "John", "age": 20 }.
{ "name": "Jane", "age": 23 }
]
JSON data can be accessed either by dot operator or square bracket syntax [].
Let us see its example.
Source Code
<script type="text/javascript">
const users = {
"name": "Jane",
"age": 45,
"expert": {
"js" : true,
"php" : false,
"mysql" : "true"
},
"company" : ["A", "B", "C"]
}
</script>
Source Code
<script type="text/javascript">
// JSON object
const user = {
"name": "Jane",
"age": 22
}
</script>
You can convert JSON data to a JavaScript object using the built-in JSON.parse()
function.
const jsonData = '{ "name": "John", "age": 22 }';
const obj = JSON.parse(jsonData);
console.log(obj.name); // John
Source Code
<script type="text/javascript">
const jsonTxt = '{"name":"John Doe", "age":35, "city":"Mumbai"}'
const obj = JSON.parse(jsonTxt);
</script>
You can also convert JavaScript objects to JSON format using the JavaScript built-in JSON.stringify()
function. For example.
const jsonData = { name : "John", age: 22 };
const obj = JSON.stringify(jsonData);
Source Code
<script type="text/javascript">
//json object
const jsonData = { name: "John", age: 22 };
// converting to JSON
const obj = JSON.stringify(jsonData);
</script>