Site icon Coding is Love

JSON Master : In-depth JSON tutorial for Beginners

Json tutorial

JSON stands for JavaScript Object Notation. After writing this previous post on JSON, I’ve been receiving a lot of queries about how to parse different JSON structures and how to create JSON. So I’m writing this post to make JSON understandable for everyone. Let’s get started!

Update: This article is still relevant in 2020

What is JSON?

JSON is a data exchange format. Let’s make it simple – JSON is a format in which data is sent or received so that it’s easy to read the data.

Can you give me one more example of data exchange format?

XML is another example of data exchange format. XML was widely used before JSON gained popularity. XML is used even today but JSON kicks XML’s ass any day 😀

Show me a practical example that uses JSON?

JSON is used everywhere. One simple example – Youtube API. If I want to pull trending videos in US then I can call youtube API which gives response in JSON format which looks like image below.

Explore a wide list of JSON APIs here – Public JSON API list

Understanding JSON (Read this clearly)

Now that you know how JSON looks and its practical use cases, Let’s try to understand the structure of JSON.

JSON is built with just 2 data types – Object/Dictionary and Array.

Any valid JSON is always a Key-value pair object (dictionary) or an Array or a combination of both.

The one line just above this is all you need to master JSON. Most of them fail to understand this in the beginning.

Object

An object is a set of key-value pairs. An object begins with { and ends with } . Key-value pairs are separated by a comma.

Object is realized as different data types in different languages.

Its basically a collection of keys and values. Here’s an example below.

{
    name: "Coding is Love",
    url: "https://codingislove.com"
}

An Object’s keys should always be a string in JSON. So it should be wrapped in quotes. Although regular object’s keys need not be wrapped in strings as shown in example above. So Object in JSON looks like this –

{
    "name": "Coding is Love",
    "url": "https://codingislove.com"
}

An Object’s values are usually accessed by specifying its property/keys’s name. Example in Javascript :

var siteData = {
name: "Coding is Love",
url : "https://codingislove.com"
}
console.log(siteData.name)        //logs "Coding is Love"
console.log(siteData.url)        //logs "https://codingislove.com"
console.log(siteData["name"])    //logs "Coding is Love"

It is accessed the same way in most programming languages. The syntax might change a bit but the basic concept remains the same. Access Values using it’s Key.

Note: Dictionaries in VBA can be accessed using siteData("name")

Array

An Array is a collection of values separated by comma. It starts with [ and ends with ]

Example :

["Name 1","Name 2","Name 3","Name 4"]


Array values are accessed by specifying Index. Array index start with 0.

var namesList = ["Name 1","Name 2","Name 3","Name 4"];
console.log(namesList[0]) //Logs "Name 1"
console.log(namesList[3]) //Logs "Name 4"

Note: If you are using VBA-JSON in Excel VBA then it converts arrays into collections whose index start with 1 and can be accessed like this – namesList(1)

JSON Examples

If you understand Objects and arrays then JSON is very simple. Let’s see few possible ways in which JSON can be built.

JSON with Object

{
    "name": "Coding is Love",
    "url": "https://codingislove.com",
    "email": "admin@codingislove.com",
    "job": "Writing awesome content",
    "phone": 1234567890
}

JSON with Array

[1,2,3,4,5,6,7]

JSON with Array of objects

[
  {
    "userId": 1,
    "id": 1,
    "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
    "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
  },
  {
    "userId": 1,
    "id": 2,
    "title": "qui est esse",
    "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
  }
]

Object inside an object

{
    "id": 1,
    "name": "Leanne Graham",
    "username": "Bret",
    "email": "Sincere@april.biz",
    "address": {
        "street": "Kulas Light",
        "suite": "Apt. 556",
        "city": "Gwenborough",
        "zipcode": "92998-3874",
        "geo": {
            "lat": "-37.3159",
            "lng": "81.1496"
        }
    }
}

Array inside object

{
    "id": 1,
    "profile": {
        "name": "John Doe",
        "Photos": ["url1", "url2"]
    }
}

So, Basically we can dump objects, arrays inside each other in any way we want and build a valid JSON as long as we follow the rules of Array and Object.

Parse JSON in different Languages

Few languages have built-in support for JSON and few don’t. Let’s see how to Build JSON and parse JSON in few languages.

Javascript

Javascript has built-in methods :

  1. JSON.Stringify(JSON Object) – Converts JSON Object to string. Usually used when sending data to server.
    var mydata = {name:"Coding is Love",score:25};
    var JsonString = JSON.Stringify(mydata);
    //post JsonString to server
    
  2. JSON.Parse(JSON String) – Converts JSON string into object which can be used to access the data. It is usually used when data is received from external source and parse data in it.
    var mydata = get JSON from your external source
    //lets say we are pulling the data that we posted from previous example.
    parsedObject = JSON.parse(mydata)
    alert(parsedObject.score) //alerts 25
    

Similar methods to parse and stringify JSON exist in most languages.

Python

Python has built-in JSON Encoder and Decoder. Documentation here – https://docs.python.org/2/library/json.html

import json
json.loads(JSON String)
json.dumps(Dictionary)

PHP

PHP also has built-in methods for parsing JSON. Documentation here – http://php.net/manual/en/book.json.php

json_decode(JSON string)
json_encode(Associative array)

VBA

There’s an in-detail post here – Parse JSON in Excel

Ruby

There’s a ruby gem here – https://github.com/flori/json

require 'json'
JSON.parse(string)
JSON.generate(object)

Wrapping up

If you read this post completely then I’m sure you’ve understood JSON! Now, Try using it in real life.

Need some learning project? Let’s say you want to build a custom website which shows only a particular set of youtube videos. Hit the youtube API, parse the JSON and become a JSON master!

If you have any questions or feedback, comment below.

Exit mobile version