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
- {
- name: values,
- name2: values2
- }
So here is a very simple example curly braces representing json object, name values pair separated by comma:
- {
- "Name" :"Ravi",
- "City": "Varanasi",
- }
More complex example
- {
- "countryId": 1,
- "countryName" : "India",
- "state" : ["uttar pradesh","Mumbai","Bangalore"]
- }
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
- [
- {
- "AlbumId": 3,
- "GenreId": 1,
- "ArtistId": 4,
- },
- {
- "AlbumId": 5,
- "GenreId": 1,
- "ArtistId": 77,
- }]
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.