JSON, stands for Javascript Object Notation. The way we define JSON is as follows
const jsonObject = {
"key1" : function value1() {},
"key2" : "value2",
"key3" : true,
"key4" : false,
"key5" : ["value6","value7","value8","value9"],
"key6" : new Date(),
"key7" : { "key1":"hello" , "key2":"world"},
"key8" : 8
}As you can see a JSON is map of key and value pairs:
- Must start with a
{and end with a} - With and
keyandvalueseperated by: keyandvaluepair seperated by,coma except for the last pair, there is no coma after the last pair.keymust always be a string.valuecan be anything for eg: Another JSON, a function, an array, a string, a boolean,a Date object etc.- same
keycannot be repeated inside of a JSON.
There are two ways to access a JSON's property:
jsonObject.key1 you can use the dot operator when key is known to you while coding.
But there are some cases when the key is not known or obtained during execution of some logic in that case:
const someKey = "key3"
jsonObject[someKey]
//this is valid because during runtime or during execution the variable someKey will be replaced by the value inside it.
// also the below code is also valid
jsonObject["key3"]
// you can also call this as indexed based access by imagining the json as a named array.JSON as a keyword is also made available by the js runtime environment both in the browser and in the server,
you can call JSON.stringify(someJSON) method and JSON.parse(someString) method
stringify(): this method will convert the json object to stringparse(): if your string looks like a json in format, this function will convert the string into JSON else it will throw and error.
Some additional reading
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode https://en.wikipedia.org/wiki/Associative_array https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON
