- Overview
- Table of Contents
- The Document Object Model
- DOM and Java
- DOM and JavaScript
- DOM and .NET
- DOM and C++
- DOM and Perl
- DOM and PHP
- DOM Level 3
- The Simple API for XML (SAX)
- SAX and Java
- SAX and .NET
- SAX and Perl
- SAX and PHP
- Validation
- Document Type Definitions (DTDs)
- XML Schemas
- RELAX NG
- Schematron
- Validation in Applications
- XSL Transformations (XSLT)
- XSLT in Java
- XSLT and RSS in .NET
- XSL-FO
- XPath
- XML Base
- XHTML
- XHTML 2.0
- Cascading Style Sheets
- XUL
- XML Events
- XML Data Binding
- XML and Databases
- SQL Server and FOR XML
- Service Oriented Architecture
- Web Services
- Apache Axis2
- REST
- SOAP
- SOAP and Java
- WSDL
- UDDI
- XML-RPC
- Ajax
- JSON
- Ruby on Rails
- Web Services Security
- SAML
- XML Digital Signatures
- XML Key Management Services
- Internationalization
- Grid Computing
- Web Services Resource Framework
- WS-Addressing
- WS-Notifications
- New Languages: XML in Use
- Google Web Toolkit
- Google Sitemaps
- Accessibility
- The Semantic Web
- WML
- Google Web Services
- The Yahoo! Web Services Interface
- eBay REST API
- WordML
- DocBook
- XML Query
- XForms
- Resource Description Framework (RDF)
- Topic Maps
- Rich Site Summary (RSS)
- Simple Sharing Extensions (SSE)
- Atom
- Podcasting
- Scalable Vector Graphics (SVG)
- OPML
- Summary
- Projects
- Additional Resources
JSON
Last updated Jan 26, 2006.
Normally, when we think of Web services, we think about XML going back and forth. That's only natural, given the preponderance of SOAP and REST of applications, but it isn't actually the only way to do things. Today we're going to talk about JavaScript Object Notation (JSON). JSON is a way to represent the data and methods of an object in a text string, which enables you to reconstitute it as an object on demand.
There are several advantages to using JSON over XML. For one thing, it's much less verbose, which is good if you are passing large amounts of data. For another thing, your logic and structure or already in place when he received the object. You don't need to re-create them. Also, as we'll see in this section, there are certain advantages in terms of Web applications and the avoidance of cross domain restrictions.
On the other hand, JSON can be very difficult to read if you're a human instead of a computer. For example, consider this representation of time data for a project:
{"project": {"ProjectName":"InformIT Column",
"TotalTime":"3289",
"LastWorkedOn": {
"Day":24,
"Month":1,
"Year":2006 },
"TimeThisWeek":"135",
"TimeToday":"20",
"CurrentProject":"JSON Guide Entry"}}
Now, I'm sure that there are people who have no trouble separating the labels
(such as ProjectName) from the data (such as InformIT Column), but I'm not one of them.
But let's look at the structure so we can see how this works.
We start with the fact that the entire object is placed within curly braces ({}).
Then we have the actual object name, project, followed by the contents of the object, also in braces.
Each member is signified by a label, the colon, and its value. In some cases, we have a complex object. For example,
LastWorkedOn is actually an object itself, as you can tell because its value is enclosed in curly braces.
That object has three members, Day, Month, and Year. And
Let's see how this would actually work in JavaScript. Start by creating a basic page with a script:
<html>
<head>
<title>JSON testing</title>
<script type="text/javascript">
function showObject(){
var str = '{"project": {'+
'"ProjectName":"InformIT Column",'+
'"TotalTime":"3289",'+
'"LastWorkedOn": {'+
' "Day":24,'+
' "Month":1,'+
' "Year":2006 },'+
'"TimeThisWeek":"135",'+
'"TimeToday":"20",'+
'"CurrentProject":"JSON Guide Entry"}}';
var projectObj = eval("("+str+")");
document.write("Project is: "+projectObj.project.ProjectName);
document.write("<br />");
document.write("Last worked on: "+
projectObj.project.LastWorkedOn.Month + "/" +
projectObj.project.LastWorkedOn.Day + "/" +
projectObj.project.LastWorkedOn.Year);
}
</script>
</head>
<body>
<h1>JavaScript Object Notation</h1>
<script type="text/javascript">
showObject();
</script>
</body>
</html>
Year we've created a simple script that includes the text that represents the object. We then use the
eval () function to convert the text (enclosed in parentheses) back into an object. (If you're
concerned about the security implications of using the eval() function, fear not. We'll get to that shortly.)
Once we have the object, we can access its data just as we would access the data of any other JavaScript object.
Here you see the project name, and the contents of the LastWorkedOn object. Finally,
we call the script from within the body of the page. The results look like this:
We can also use JSON to specify arrays. For example, we might have a projects
object with more than one project:
...
function showArrayOfObjects(){
var str = '{"project": [{'+
'"ProjectName":"InformIT Column",'+
'"TotalTime":"3289",'+
'"LastWorkedOn": {'+
' "Day":24,'+
' "Month":1,'+
' "Year":2006 },'+
'"TimeThisWeek":"135",'+
'"TimeToday":"20",'+
'"CurrentProject":"JSON Guide Entry"},'+
'{'+
'"ProjectName":"Vitamin Store Site",'+
'"TotalTime":"42",'+
'"LastWorkedOn": {'+
' "Day":20,'+
' "Month":1,'+
' "Year":2006 },'+
'"TimeThisWeek":"2",'+
'"TimeToday":"0",'+
'"CurrentProject":"Client Review"}]}';
var projectObj = eval("("+str+")");
document.write("First project is: "+projectObj.project[0].ProjectName);
document.write("<br />");
document.write("Last worked on: "+
projectObj.project[0].LastWorkedOn.Month + "/" +
projectObj.project[0].LastWorkedOn.Day + "/" +
projectObj.project[0].LastWorkedOn.Year);
document.write("<br /><br />");
document.write("Second project is: "+projectObj.project[1].ProjectName);
document.write("<br />");
document.write("Last worked on: "+
projectObj.project[1].LastWorkedOn.Month + "/" +
projectObj.project[1].LastWorkedOn.Day + "/" +
projectObj.project[1].LastWorkedOn.Year);
}
</script>
</head>
<body>
<h1>JavaScript Object Notation</h1>
<script type="text/javascript">
showArrayOfObjects();
</script>
</body>
</html>
Notice first of all that I have enclosed the individual elements of the array in brackets ([]).
In this case, we're dealing with an array of objects, but it could just as easily have been an array of strings or
numbers, as long as everything is enclosed in brackets and separated by commas.
Once we have the object, again we work with it like any other object; we are specifying a specific element of the array, which gives us the object in that position, which we treat like any other object. The results look like this:
That's the basic idea, but now we need to do with this eval() thing. You see, this function
will execute any code you give it, even if it comes in as a string. This is terrific for executing dynamically
generated code, but terrifying if you are getting the text from an outside source. So in general,
it's not a good idea to create your objects with a raw call to the eval() function. Instead,
you'll want to use a JSON parser. You can download one from here. In fact,
you can download JSON parsers for virtually any language from JSON.org.
Once you have the parser, you can use it to create your objects:
<html>
<head>
<title>JSON testing</title>
<script type="text/javascript" src="./json.js" ></script>
<script type="text/javascript">
function showArrayOfObjectsWithParser(){
var str = '{"project": [{'+
...
'"CurrentProject":"Client Review"}]}';
var projectObj = JSON.parse(str);
document.write("First project is: "+projectObj.project[0].ProjectName);
document.write("<br />");
...
}
</script>
</head>
<body>
<h1>JavaScript Object Notation</h1>
<script type="text/javascript">
showArrayOfObjectsWithParser();
</script>
</body>
</html>
Once we include the parser with its own script tag, the only change is the way in which we create the object.
Notice that we are no longer enclosing a string in parentheses. Other than that, everything is exactly the same.
Okay, now that we know how to use these objects, let's put them to work in a more practical situation.
Yahoo Web Services now gives you the option to output JSON text rather than XML. For example, the query:
http://api.search.yahoo.com/ImageSearchService/V1/imageSearch?appid=YahooDemo&query=Madonna&results=2&output=json
(scroll to the right to see the new parameter)
will return the string:
{"ResultSet":{
"totalResultsAvailable":"305090",
"totalResultsReturned":2,
"firstResultPosition":1,
"Result":[{
"Title":"madonna 118",
"Summary":"Picture 118 of 184",
"Url":"http:\/\/www.celebritypicturesarchive.com\/pictures\/m\/madonna\/madonna-118.jpg",
"ClickUrl":"http:\/\/www.celebritypicturesarchive.com\/pictures\/m\/madonna\/madonna-118.jpg",
"RefererUrl":"http:\/\/www.celebritypicturesarchive.com\/pgs\/m\/Madonna\/Madonna%20picture_118.htm",
"FileSize":"40209",
"FileFormat":"jpeg",
"Height":"700",
"Width":"473",
"Thumbnail":{
"Url":"http:\/\/re2.mm-b1.yimg.com\/image\/500892420",
"Height":"130",
"Width":"87"}},
{...}]}}
instead of the XML:
<?xml version="1.0" encoding="UTF-8"?>
<ResultSet xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="urn:yahoo:srchmi"
xsi:schemaLocation="urn:yahoo:srchmi http://api.search.yahoo.com/ImageSearchService/V1/ImageSearchResponse.xsd"
totalResultsAvailable="305090"
totalResultsReturned="2"
firstResultPosition="1">
<Result>
<Title>madonna 118</Title>
<Summary>Picture 118 of 184</Summary>
<Url>http://www.celebritypicturesarchive.com/pictures/m/madonna/madonna-118.jpg</Url>
<ClickUrl>http://www.celebritypicturesarchive.com/pictures/m/madonna/madonna-118.jpg</ClickUrl>
<RefererUrl>http://www.celebritypicturesarchive.com/pgs/m/Madonna/Madonna%20picture_118.htm</RefererUrl>
<FileSize>40209</FileSize>
<FileFormat>jpeg</FileFormat>
<Height>700</Height>
<Width>473</Width>
<Thumbnail>
<Url>http://re2.mm-b1.yimg.com/image/500892420</Url>
<Height>130</Height>
<Width>87</Width>
</Thumbnail>
</Result>
<Result>...</Result>
</ResultSet>
The data is the same, but it's returned in JSON format.
Okay, so how do we use it? Well, we use it by feeding it to a script, just as we would use any other data.
For example, we can create a script that extract the number of results and adds it to an empty
div:
<html>
<head>
<title>JSON testing</title>
<script type="text/javascript" src="./json.js" ></script>
<script type="text/javascript">
function getNumberOfResults(){
var yahooStr = '{"ResultSet":{"totalResultsAvailable":"305090","totalResultsReturned":2,"firstResultPosition":1,"Result":[{"Title":"madonna 118","Summary":"Picture 118 of 184","Url":"http:\/\/www.celebritypicturesarchive.com\/pictures\/m\/madonna\/madonna-118.jpg","ClickUrl":"http:\/\/www.celebritypicturesarchive.com\/pictures\/m\/madonna\/madonna-118.jpg","RefererUrl":"http:\/\/www.celebritypicturesarchive.com\/pgs\/m\/Madonna\/Madonna%20picture_118.htm","FileSize":"40209","FileFormat":"jpeg","Height":"700","Width":"473","Thumbnail":{"Url":"http:\/\/re2.mm-b1.yimg.com\/image\/500892420","Height":"130","Width":"87"}},{"Title":"madonna britney spe 111697a","Summary":"Britney og Madonna kom sv\u00e6rt n\u00e6r hverandre under MTVutdelingen","Url":"http:\/\/pub.tv2.no\/multimedia\/TV2\/archive\/00111\/madonna_britney_spe_111697a.jpg","ClickUrl":"http:\/\/pub.tv2.no\/multimedia\/TV2\/archive\/00111\/madonna_britney_spe_111697a.jpg","RefererUrl":"http:\/\/pub.tv2.no\/TV2\/underholdning\/article140732.ece","FileSize":"21801","FileFormat":"jpeg","Height":"200","Width":"250","Thumbnail":{"Url":"http:\/\/re2.mm-c1.yimg.com\/image\/979408253","Height":"88","Width":"110"}}]}}';
var yahooObj = JSON.parse(yahooStr);
document.getElementById("resultDiv").innerHTML =
"<b>Results: </b>"+yahooObj.ResultSet.totalResultsAvailable;
}
</script>
</head>
<body>
<h1>JavaScript Object Notation</h1>
<div id="resultDiv"></div>
<a href="javascript:getNumberOfResults()">Get Results</a>
</body>
</html>
Starting at the bottom, we created the div, and a link to the getNumberOfResults()
function. That function has the hardcoded string that represents the object (we'll change that in a minute),
parses it, and adds the results to the div. When you first load the page, all you will see is the link.
Once you click the link, you'll see the results:
That's all well and good, but how do we get the information loaded with the page? Well, consider this page:
<html>
<head>
<title>JSON testing</title>
<script type="text/javascript" src="./json.js" ></script>
<script type="text/javascript">
function showNumberOfResults(yahooStr){
var yahooObj = JSON.parse(yahooStr);
document.getElementById("resultDiv").innerHTML =
"<b>Results: </b>"+yahooObj.ResultSet.totalResultsAvailable;
}
</script>
</head>
<body>
<h1>JavaScript Object Notation</h1>
<div id="resultDiv"></div>
<script type="text/javascript">
var yahooStr = '{"ResultSet":{"totalResultsAvailable":"305090","totalResultsReturned":2,"firstResultPosition":1,"Result":[{"Title":"madonna 118","Summary":"Picture 118 of 184","Url":"http:\/\/www.celebritypicturesarchive.com\/pictures\/m\/madonna\/madonna-118.jpg","ClickUrl":"http:\/\/www.celebritypicturesarchive.com\/pictures\/m\/madonna\/madonna-118.jpg","RefererUrl":"http:\/\/www.celebritypicturesarchive.com\/pgs\/m\/Madonna\/Madonna%20picture_118.htm","FileSize":"40209","FileFormat":"jpeg","Height":"700","Width":"473","Thumbnail":{"Url":"http:\/\/re2.mm-b1.yimg.com\/image\/500892420","Height":"130","Width":"87"}},{"Title":"madonna britney spe 111697a","Summary":"Britney og Madonna kom sv\u00e6rt n\u00e6r hverandre under MTVutdelingen","Url":"http:\/\/pub.tv2.no\/multimedia\/TV2\/archive\/00111\/madonna_britney_spe_111697a.jpg","ClickUrl":"http:\/\/pub.tv2.no\/multimedia\/TV2\/archive\/00111\/madonna_britney_spe_111697a.jpg","RefererUrl":"http:\/\/pub.tv2.no\/TV2\/underholdning\/article140732.ece","FileSize":"21801","FileFormat":"jpeg","Height":"200","Width":"250","Thumbnail":{"Url":"http:\/\/re2.mm-c1.yimg.com\/image\/979408253","Height":"88","Width":"110"}}]}}';
</script>
<a href="javascript:showNumberOfResults(yahooStr)">Get Results</a>
</body>
</html>
Because of the number of nested quotation marks, I've created a variable and called it from the function,
but you can see that all we're doing here is passing the JSON object to a function. Now, what if we could
have the request for data call the function itself? It turns out that if we add a callback parameter
to the request, we can actually have a call a function. For example:
<html>
<head>
<title>JSON testing</title>
<script type="text/javascript" src="./json.js" ></script>
<script type="text/javascript">
function showNumberOfResults(yahooObj){
document.getElementById("resultDiv").innerHTML =
"<b>Results: </b>"+yahooObj.ResultSet.totalResultsAvailable;
}
</script>
</head>
<body>
<h1>JavaScript Object Notation</h1>
<div id="resultDiv"></div>
<script type="text/javascript" src="http://api.search.yahoo.com/ImageSearchService/V1/imageSearch?appid=YahooDemo&query=Madonna&results=2&output=json&callback=showNumberOfResults" ></script>
</body>
</html>
Again starting at the bottom, we are creating a script tag that has as its source the actual YWS request. If you scroll all the way to the right, you'll see that we've added a new parameter:
&callback=showNumberOfResults
What this does is tell Yahoo! To return a call to the showNumberOfResults
script, passing the object as a parameter. If you then look at the top of the page, we slightly altered that function to take the object
rather than the string. When the page loads, the browser comes to this tag, loads the source, and calls the function.
If you load this page, you will see the number of results after a slight delay:
This still leaves us with one problem: how do we create a page that takes data from the user -- such as the
keyword they want to search on -- and returns the results to the browser? The answer lies in the
script tag. In this case, we hardcoded it onto the page. But what if we created it dynamically, in response to
a user action? Try this:
<html>
<head>
<title>JSON testing</title>
<script type="text/javascript" src="./json.js" ></script>
<script type="text/javascript">
function showLiveResults(yahooObj){
document.getElementById("resultDiv").innerHTML =
"<b>Results: </b>"+yahooObj.ResultSet.totalResultsAvailable;
}
function makeResultScript(){
var form = document.getElementById("keywordForm");
var keyword = form.elements["keyword"].value;
var url = "http://api.search.yahoo.com/ImageSearchService/V1/imageSearch?appid=YahooDemo"+
"&query="+keyword+
"&results=2&output=json&callback=showLiveResults";
headElement = document.getElementsByTagName("head").item(0);
var scriptTag = document.createElement("script");
scriptTag.setAttribute("type", "text/javascript");
scriptTag.setAttribute("src", url);
headElement.appendChild(scriptTag);
}
</script>
</head>
<body>
<h1>JavaScript Object Notation</h1>
<div id="resultDiv"></div>
<form id="keywordForm">
Keyword: <input type="text" name="keyword" />
<input type="button" onclick="makeResultScript()" value="Get Number Of Results" />
</form>
</body>
</html>
Starting once again at the bottom, we've created a form. That form takes a keyword, and when you click the
button, it calls the makeResultScript() function. That function gets a reference to the form, from which
it extracts the keyword the user has chosen. It then uses that keyword to create the appropriate URL for the request.
(Notice that we've changed the name of the function to showLiveResults.) It then gets a reference to the
head element, and then creates a new script element with the appropriate
type and src element.
The moment it adds that element to the head element, the call goes out to the Web service,
and when it comes back, the object is fed to the showLiveResults function. That function simply
extracts the data and adds it to the page, just as we've been doing all along. The result is a page in which you can
at a keyword and get the number of results almost instantly:
There's just one more thing left to do: remove the clutter. We've now added a new tag to the DOM, so let's go about removing it in case we want to make another request:
<html>
<head>
<title>JSON testing</title>
<script type="text/javascript" src="./json.js" ></script>
<script type="text/javascript">
var scriptCounter = 1;
function showLiveResults(yahooObj){
document.getElementById("resultDiv").innerHTML = "<b>Results: </b>"+yahooObj.ResultSet.totalResultsAvailable;
var scriptTag = document.getElementById(scriptCounter);
headElement = document.getElementsByTagName("head").item(0);
headElement.removeChild(scriptTag);
scriptCounter++;
}
function makeResultScript(){
var form = document.getElementById("keywordForm");
var keyword = form.elements["keyword"].value;
var url = "http://api.search.yahoo.com/ImageSearchService/V1/imageSearch?appid=YahooDemo"+
"&query="+keyword+
"&results=2&output=json&callback=showLiveResults";
headElement = document.getElementsByTagName("head").item(0);
var scriptTag = document.createElement("script");
scriptTag.setAttribute("id", scriptCounter);
scriptTag.setAttribute("type", "text/javascript");
scriptTag.setAttribute("src", url);
headElement.appendChild(scriptTag);
}
</script>
...
When we create the script tag, we give it a unique id attribute,
based on the scriptCounter variable. When the script has been executed, we then
use standard DOM techniques to remove it from the document, incrementing the counter as we go.
You shouldn't see any change in the document, but you should be able to make multiple requests
without reloading the page.
And there you have it. Accessing a Web service from the browser without reloading and without having to use a proxy to avoid cross domain problems. And it's fast, too. Yahoo! Is not the only web service that provides JSON data, either. You can also use this technique with del.icio.us, and I wouldn't be surprised if other services jumped on the bandwagon in the near future.





Account Sign In
View your cart