ColdFusion解析JSON

我已经按照Adobe Help / DeserializeJSON文档进行了操作,但它给出了自定义脚本模块中的错误或者CFDATA中未定义的元素COLUMNS等错误.任何帮助深表感谢.错误来自cfData.使用cfData执行任何操作都会导致某些错误.倾倒cfData工作正常.它显示了所有正确的数据.以下是我的代码:

<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>

最佳答案 查看转储,deserializeJSON的结果是结构,而不是查询.您可以使用structKeyExists()函数测试cfData中是否存在天气.下面的代码运行没有错误:

<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>
点赞