I have followed this Adobe Help/DeserializeJSON documentation but it's giving me errors like Error in custom script module or Element COLUMNS is undefined in CFDATA. Any help is much appreciated. The error comes from cfData. Doing anything with cfData will cause some kind of errors. Dumping cfData works fine though. It shows all the correct data. Below is my code:
<cfhttp url="http://api.openweathermap.org/data/2.5/weather?zip=55101,us&appid=44db6a862fba0b067b1930da0d769e98" method="get" >
<!--- JSON data is sometimes distributed as a JavaScript function.
The following REReplace functions strip the function wrapper. --->
<cfset theData=REReplace(cfhttp.FileContent, "^\s*[[:word:]]*\s*\(\s*","")>
<cfset theData=REReplace(theData, "\s*\)\s*$", "")>
<!---<cfdump var="#theData#" >--->
<!--- Test to make sure you have JSON data. --->
<cfif !IsJSON(theData)>
<h3>The URL you requested does not provide valid JSON</h3>
<!--- If the data is in JSON format, deserialize it. --->
<cfelse>
<cfset cfData=DeserializeJSON(theData)>
<cfdump var=#cfData# >
<cfset colList=ArrayToList(cfData.COLUMNS)>
<cfset weatherIdx=ListFind(colList, "weather")>
<cfset descriptionIdx=ListFind(colList, "description")>
<!--- Now iterate through the DATA array and display the data. --->
<cfoutput>
<cfloop index="i" from="1" to="#Arraylen(cfData.DATA)#">
<h3>Weather: #cfData[i][weatherIdx]#</h3>
<h4>Discription: #cfData[i][descriptionIdx]#</h4>
</cfloop>
</cfoutput>
</cfif>
Looking at your dump, the result of deserializeJSON is a struct, not a query. You can test to see if weather
exists in cfData
using the structKeyExists()
function. The code below runs for me without error:
<cfhttp url="http://api.openweathermap.org/data/2.5/weather?zip=55101,us&appid=44db6a862fba0b067b1930da0d769e98" method="get" >
<!--- JSON data is sometimes distributed as a JavaScript function.
The following REReplace functions strip the function wrapper. --->
<cfset theData=REReplace(cfhttp.FileContent, "^\s*[[:word:]]*\s*\(\s*","")>
<cfset theData=REReplace(theData, "\s*\)\s*$", "")>
<!---<cfdump var="#theData#" >--->
<!--- Test to make sure you have JSON data. --->
<cfif !IsJSON(theData)>
<h3>The URL you requested does not provide valid JSON</h3>
<!--- If the data is in JSON format, deserialize it. --->
<cfelse>
<cfset cfData=DeserializeJSON(theData)>
<cfdump var=#cfData# >
<cfif structKeyExists( cfData, 'weather' ) AND isArray(cfData.weather)>
<cfoutput>
<cfloop index="i" from="1" to="#arrayLen(cfData.weather)#">
<h3>Weather: #cfData.weather[i].main#</h3>
<h4>Description: #cfData.weather[i].description#</h4>
</cfloop>
</cfoutput>
</cfif>
</cfif>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With