Skip to content

Instantly share code, notes, and snippets.

@siddrc
Last active May 13, 2018 20:39
Show Gist options
  • Select an option

  • Save siddrc/047fd7220684d8251c9b8751d70d91a3 to your computer and use it in GitHub Desktop.

Select an option

Save siddrc/047fd7220684d8251c9b8751d70d91a3 to your computer and use it in GitHub Desktop.
JSON

json

Introduction

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:

  1. Must start with a { and end with a }
  2. With and key and value seperated by :
  3. key and value pair seperated by , coma except for the last pair, there is no coma after the last pair.
  4. key must always be a string.
  5. value can be anything for eg: Another JSON, a function, an array, a string, a boolean,a Date object etc.
  6. same key cannot 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

  1. stringify() : this method will convert the json object to string
  2. parse() : 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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment