An Introduction To JSON

Introduction to JSON

 
In this article, we will discuss the first two points from the following. In upcoming articles, I will discuss how to create a JSON file from a database table.
  • Introduction to JSON
  • JSON syntax
  • Parsing and Generating JSON files
  • JSON data storage application
So let us start with the introduction part. 
 

What is JSON?

 
JSON (Javascript Object Notation) is a lightweight data-interchange format.
 
Why use it
  • Same syntax as JavaScript objects.
  • Easy for humans to read and write.
  • Language independent.
  • It can be used to store application data.

How can we create /read JSON file?

 
We can create/read a JSON file by using:
  • JavaScriptSerializer (inbuilt in dotnet framework).
  • JSON.NET third party tool (download from Nuget Package Manager).
So let us look at JSON:
 
{ } culry braces represent object
key – value pair 
 
JSON Syntax
 
So what exactly makes up a JSON file:
  • Values
  • Objects
  • Arrays
  • Putting it all together
JSON Values can be
  • Strings ( in double quotes)
  • Numbers (integer or floating point)
  • Boolean ( true or false )
  • Objects ( in curly brackets)
  • Array( in square brackets)
  • Null
JSON Object
  • Name/value pairs using colons
  • Enclose by curly braces
  • Pairs separated by commas
Example
  1. {    
  2.    name: values,    
  3.    name2: values2    
  4. }   
So here is a very simple example curly braces representing json object, name values pair separated by comma:
  1. {    
  2.    "Name" :"Ravi",    
  3.    "City""Varanasi",    
  4. }   
More complex example
  1. {    
  2.    "countryId": 1,    
  3.    "countryName" : "India",    
  4.    "state" : ["uttar pradesh","Mumbai","Bangalore"]    
  5. }   
Again we have curly braces representing object. This time we have three name-value pairs: countryId is just integer, countryName is string and state is arrays shown by bracket,
 

JSON Arrays

  • Values enclosed by brackets
  • Separated by commas [item,item,item,item]
Example
 
["uttar pradesh","Mumbai","Bangalore"]
 
Indicated by bracket we have JSON arrays and in this example its an array of three string and each string separated by commas:
 
[1,2,3,4] its array of number
 
Complex array
  1. [    
  2. {    
  3.     "AlbumId": 3,    
  4.     "GenreId": 1,    
  5.     "ArtistId": 4,    
  6. },    
  7. {    
  8.     "AlbumId": 5,    
  9.     "GenreId": 1,    
  10.     "ArtistId": 77,    
  11. }]   
So array can be a collection of anything including object and these objects have three name-value pairs.
 
Putting it all together
  • JSON values can also be objects or arrays
  • JSON objects and arrays can be nested
 
Points of Interest
  • In this article, I have touched the very basics of JSON.
  • JSON is very useful in client-server communication where network bandwidth is very limited.


Recommended Ebook

Voice of a Developer: JavaScript From Scratch

Download Now!
Similar Articles