ColdFusion: Parse Yahoo! Web Service REST Calls

This HOWTO assumes that you already know how to make a Yahoo! Web Service request, and are wondering how to parse the XML or JSON returned by your request. This page contains these sections:

Parsing JSON

In addition to XML, some Yahoo! Web Services can also return JavaScript Object Notation (JSON). JSON is a compact data notation that has some advantages over XML. Not all Yahoo! Web Services are capable of returning JSON. For details on JSON, consult our JSON documentation.

ColdFusion does not have native support for JSON (although it has been announced for the next version). There are a few open source projects for generating and consuming JSON. This tutorial will use the CFJSON project by Jehiah Czebotar and Thomas Messier. You can find out more about project at it's web site: http://www.epiphantastic.com/cfjson/index.php

Once you've downloaded the project and extracted the CFC, you need to create an instance of it:

<cfset json = createObject("component", "json")>

After you have an instance of the json component, you can then use it to convert a JSON based response to a native ColdFusion object:

<cfset data = json.decode(response)>

Remember that you must explicitely tell Yahoo's services to return JSON:

<cfset requestURL = "http://api.search.yahoo.com/ImageSearchService/V1/imageSearch?appid=YahooDemo&query=Madonna&results=4&output=json">

A complete code sample is available here.

Parsing XML With ColdFusion

ColdFusion MX supports XML parsing directly in the language. To translate an XML string into a native XML object in ColdFusion, simply use the xmlParse function:

<cfset xmlResult = xmlParse(result)>

ColdFusion makes it very easy to work with this result. For example, most Yahoo services return a value that represents the total number of results. You can retreive this value from the XML object by simply accessing the path in the XML object:

<cfset totalResults = xmlResult.resultSet.xmlAttributes.totalResultsAvailable>

To see all the values in an XML object, you can simply dump it:

<cfdump var="#totalResults#">

To loop over the results from the response, you can treat the XML object like an array and loop over each result:

<cfloop index="x" from="1" to="#arrayLen(xmlResult.ResultSet.Result)#">

<!--- make a quick copy for easier access --->
<cfset node = xmlResult.ResultSet.Result[x]>

<cfoutput>
<p>
#x#) <a href="#node.clickurl.xmlText#">#node.title.xmlText# (#node.url.xmlText#)</a><br />
#node.summary.xmlText#
</p>
</cfoutput>

</cfloop>

A complete code sample is available here.

For More Information

For more information on using ColdFusion with Yahoo! Web Services APIs, see The Yahoo! Developer Network ColdFusion Developer Center.