I have already written some articles concerning AJAX, now it's time to take another step and introduce JSON. Actually JSON is just a format - a standard - not a technique. However it is widely used in combination with AJAX in order to create asynchronous requests resulting in JSON data.
What is JSON?
JSON is a data format, nothing more nothing less. The same way we open a jpeg file and expect it to contain jpeg data, JSON data contains data in predefined form. The simplest example of that form would be
{ "ID": 1 }
Now, JSON is a format used to carry data, the same way XML does but in a more easy-to-read way to a human. Compare the XML with its JSON equivalent.
<ID>1</ID>
{ "ID": 1 }
JSON seems to be like reading a book in comparison to XML. JSON stands for JavaScript Object Notation. As you will see its contains use the form of an object. JSON was at first created for JavaScript, that's the reason this language is mentioned on its name. However, JSON soon became a widely acknowledged standard. Since then most platforms created libraries that support it. As a result it is quite easy to handle it. But we will come back to that later on.
JSON Syntax
JSON is written in a dictionary-like way (name value pair).
"ID": 1 refers to the name "ID" which contains the value 1. Between the name and the value a ':' character should be placed.
Keep in mind that the name part should always be contained in double quotes (") while this is not compulsory for the value part. For example numeric and boolean values need not be contained within double quotes.
To expand our simple example we will add more name value pairs.
{ "ID": 1,
"Name": "Spock",
"Species": "Half-Vulcan" }
Ok, this is a simple, yet nice, JSON expression. Now, let's go and use some JavaScript to handle it.
<script type="text/javascript">
var JSONData = {
"ID": 1,
"Name": "Spock",
"Species": "Half-Vulcan"
};
document.write(JSONData.Name + " is a " + JSONData.Species + " character.");
</script>
Running the script we get:
Spock is a Half-Vulcan character.
Quite simple, now let's create an array of pairs, expanding the one we already have, using brackets to contain the elements.
[ { "ID": 1,
"Name": "Spock",
"Species": "Half-Vulcan" },
{ "ID": 2,
"Name": "Kirk",
"Species": "Human" }
]
In order to use JavaScript to loop through all elements we could use the following code.
<script type="text/javascript">
var JSONDataArray = [{
"ID": 1,
"Name": "Spock",
"Species": "Half-Vulcan"
},
{
"ID": 2,
"Name": "Kirk",
"Species": "Human"
}];
document.write("<br/><br/>");
for (var i = 0; i < JSONDataArray.length; i++) {
var obj = JSONDataArray[i];
document.write(obj.Name + " is a " + obj.Species + " character.<br/>");
}
</script>
This time we get:
Spock is a Half-Vulcan character.
Kirk is a Human character.
Of course, the previous JSON array could be included in pure JSON format by including the whole of the array inside a value, like this.
{"StarTrek", "[ { "ID": 1,
"Name": "Spock",
"Species": "Half-Vulcan" },
{ "ID": 2,
"Name": "Kirk",
"Species": "Human" }
]}
This would be about the same thing for our handling. The only difference would be that we would have to point to the "StarTrek" name instead of handling the array right away.
<script type="text/javascript">
var StarTrekJSONDataArray = {"StarTrek" : [{
"ID": 1,
"Name": "Spock",
"Species": "Half-Vulcan"
},
{
"ID": 2,
"Name": "Kirk",
"Species": "Human"
}]};
document.write("<br/><br/>");
for (var i = 0; i < StarTrekJSONDataArray.StarTrek.length; i++) {
var obj = StarTrekJSONDataArray.StarTrek[i];
document.write(obj.Name + " is a " + obj.Species + " character.<br/>");
}
</script>
The result will still be the same
Spock is a Half-Vulcan character.
Kirk is a Human character.
As you can tell, JSON variables can become much more complex than we just created, but we have already covered the basics. Now, we said that JSON is platform independent as it is just a format and is not limited to certain platforms or languages. Let's see how this can be of help.
Server side JSON
JSON is platform independent. So, its true power does not lie in creating and handling JSON objects using JavaScript, as much as creating them server side and then handling them using JavaScript. Since everything knows what JSON is, we can create it using C#, for example, and then handle it using JavaScript. Here's how to do it.
We are going to create a simple class called StarTrekCharacter that represents Star Trek characters. This class will contain a static method called GetStarTrekCharacters() that will return all the data we have. We do not need more than three characters at the moment.
Next we create a web form using which we will get data in JSON format concerning Star Trek characters whose name matches the string we are searching. In other words, we will create a simple search engine.
Our search query will be passed using the query string. Then we will use LINQ to filter our data and return the ones we want. Finally we need to create a JavaScriptSerializer object which we will use to serialize our data in JSON form. Here's the code.
The aspx page should be completely empty as we are not creating html
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Search.aspx.cs" Inherits="JSON_Search" %>
and the code behind file
using System;
using System.Linq;
using System.Collections.Generic;
public partial class JSON_Search : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(Request.QueryString.AllKeys.Contains("query"))
{
//Get the query and use ToLower so that there is no letter case
string query = Request.QueryString["query"].ToString();
string queryToLower = query.ToLower();
List<StarTrekCharacter> searchResults = StarTrekCharacter.GetStarTrekCharacters();
//Filter results using Linq so they contain our search query
var filteredSearchResults = searchResults.Where(sr => sr.Name.ToLower().Contains(queryToLower));
//Create JavaScriptSerializer
var jsonSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
jsonSerializer.MaxJsonLength = 2147483647;
//Return serialized json data
Response.Write(jsonSerializer.Serialize(filteredSearchResults));
}
}
}
public class StarTrekCharacter
{
public int ID {get; set;}
public string Name { get; set; }
public string Species { get; set; }
public StarTrekCharacter()
{
}
//Get Data
public static List<StarTrekCharacter>> GetStarTrekCharacters()
{
List<StarTrekCharacter> StarTrekCharacters = new List<StarTrekCharacter>();
StarTrekCharacters.Add(new StarTrekCharacter() { ID = 1, Name = "Spock", Species = "Half-Vulcan" });
StarTrekCharacters.Add(new StarTrekCharacter() { ID = 2, Name = "Kirk", Species = "Human" });
StarTrekCharacters.Add(new StarTrekCharacter() { ID = 1, Name = "Scotty", Species = "Human" });
return StarTrekCharacters;
}
}
So, suppose we want to get all StarTrekCharacters whose name contains the string "s". We should request the following url
http://localhost:49808/DotNetHintsBlog/JSON/Search.aspx?query=S
The result will be
[{"ID":1,"Name":"Spock","Species":"Half-Vulcan"},{"ID":1,"Name":"Scotty","Species":"Human"}]
That's all. We got ourselves a JSON array, similar to the one we used previously. If we had called this page using JavaScript we would have our JSON data right in our hands. And that's exactly what we are going to do right now.
JSON and AJAX
In
previous articles we talked about AJAX and how we can use it to make asynchronous requests in order to get back data such as XML or pure HTML. Similarly, we can use AJAX to request JSON data. Our server control that returns JSON data is ready and set to a file called search.aspx. Now we have to create some piece of JavaScript to make it work.
This is the HTML we will use:
Keyword: <input type="text" id="KeywordInputID" />
<button onclick="search()">Search</button>
<br />
<span id="ResponseSpanID" />
We insert the keyword to the input and press the button. This will call the search method. Here's the script part.
<script type="text/javascript">
function search() {
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var JSONDataArray = JSON.parse(xmlhttp.responseText);
var text = "";
for (var i = 0; i < JSONDataArray.length; i++) {
var obj = JSONDataArray[i];
text = text + obj.Name + " is a " + obj.Species + " character. Server info!<br/>";
}
document.getElementById("ResponseSpanID").innerHTML = text
}
}
var url = "search.aspx?query=" + document.getElementById("KeywordInputID").value;
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
</script>
This is what the example looks like:
This is an AJAX request which we already know how to handle. If you need to refresh your memory check out my
previous article. The interesting part is this:
var JSONDataArray = JSON.parse(xmlhttp.responseText);
var text = "";
for (var i = 0; i < JSONDataArray.length; i++) {
var obj = JSONDataArray[i];
text = text + obj.Name + " is a " + obj.Species + " character. Server info!<br/>";
}
document.getElementById("ResponseSpanID").innerHTML = text
We use JSON.parse(xmlhttp.responseText) to parse our data to JSON format. Then we go through all items in the array the way we did earlier.
There are many things around the web asking for JSON data as an argument. As a result it is quite important to know how to ask your server for this kind of data.
Summary
JSON is a data standard used primarily in web applications to carry data in the form of objects. It uses syntax in the form of name value; however a JSON variable can end up in quite a complex form. JavaScript can easily handle JSON data and help us get the values we want. JSON can be combined with AJAX in order to get asynchronous responses carrying JSON data.