Home »
JSON
Basic syntax of JSON
JSON Syntax: In this tutorial, we are going to learn about the basic syntax of JSON (JavaScript object Notation).
Submitted by Siddhant Verma, on November 11, 2019
JSON which stands for JavaScript Object Notation is a lightweight readable data format that is structurally similar to a JavaScript object much like its name suggests.
It consists of two primary parts- keys and values which together combine to give it the form of the structure that we see. In this article, we'll explore some JSON syntax,
Key: It is a string enclosed in quotes.
Value: It can be a string, number, boolean expression, array, object, etc and is also enclosed in quotes if it's a string.
The key-value, when come in together separated by a colon, forms a key-value pair that essentially contains the data inside it. Every key-value pair is separated by a comma, much like in a normal JavaScript Object. The object is enclosed within curly braces.
{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
}
Above is an example of some JSON data. You can see how all the rules are being followed above? The file extension for a file storing key-value JSON pairs is '.json' and it has a mime type of 'application/json'.
You may say that JSON has borrowed or taken JavaScript syntax and it is very true but only to a certain extent. Since it's syntax is highly similar to that of a simple Javascript object people tend to confuse JSON as exactly like a JavaScript object. However, to break your bubble let me point out some differences, you can access a JavaScript object directly but not a JSON.
var obj={
name: 'John',
type:'wwe'
}
Obj;
Obj["name"];
Output
{name: "John", type: "wwe"}
"John"
We can't do something that we did above with JSON. Also under the key-value pairs, a typical JavaScript object can have methods as properties or the value whereas the value corresponding to a key in JSON can never be a function.
var pokemon={
name: 'Squirtle',
type: 'Water',
HP: 100,
speak: function(){
console.log(this.name+' says hi!');
}
}
undefined
pokemon.speak();
Output
Squirtle says hi!
Also, some syntax difference is there like in a JSON the key is always enclosed inside quotes unlike in a JavaScript object where the quotes enclose a key only if deemed necessary. We can say the syntax that JSON carries is essentially a subset of the syntax of a JavaScript Object, with some additions to it.