Understanding JSON

Thu, 27 Jun 2019

JSON (Javascript Object Notation) is a simple way to send and receive data between computer systems and applications. JSON is a string of plain text. Using a simple format, I can easily store numbers, arrays, strings, objects etc. This is one of the most common ways to send data between the browser and the server.

Usually frontend and backend will communicate through HTTP requests using GET, POST, DELETE operations. The requests and response data is usually in JSON format.

Let us see how to represent a simple user object in JSON format. The user has two fields - firstName and lastName. Each of the fields is represented by a key and value.

{
   "firstName" : "Jane",
   "lastName" : "Smith",
}

In the example, the key is “firstName” and the value is “Jane”. There is another key “lastName” and its value is “Smith”

Now lets add more fields to this user. Lets add a city and state fields. The user JSON data now looks like this

{
   "firstName" : "Jane",
   "lastName"  : "Smith",
   "city"      : "Austin",
   "state"     : "TX"
}

Now lets reorganize the data a bit..lets define a field called address

{
   "firstName" : "Jane",
   "lastName"  : "Smith",
   "address" : {
        "city"      : "Austin",
        "state"     : "TX"
   }
}

Lets add even more data to the address

{
   "firstName" : "Jane",
   "lastName"  : "Smith",
   "address" : {
        "street"    : "123 Main Street"
        "city"      : "Austin",
        "state"     : "TX",
        "zipCode"   : 78759
   }
}

As you see, all the data is represented as key value pairs. So “firstName” is the key , and “Jane” is the value Also “address” is the key and

    {
        "street"    : "123 Main Street"
        "city"      : "Austin",
        "state"     : "TX",
        "zipCode"   : 78759
    }

is the value.

In Javascript, we could represent a user with the above data like this

var user = {
   "firstName" : "Jane",
   "lastName"  : "Smith",
   "address" : {
        "street"    : "123 Main Street"
        "city"      : "Austin",
        "state"     : "TX",
        "zipCode"   : 78759
   }
}

If I need to print out just the “firstName” , I could say

console.log (user.firstName)

Similarly, to print the city value,

console.log (user.address.city)
Loading...