我遵循了这个 Adob​​e 帮助/DeserializeJSON 文档,但它给了我错误,例如 自定义脚本模块中的错误 元素 COLUMNS 在 CFDATA 中未定义。任何帮助深表感谢。错误来自 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 的结果是一个结构,而不是查询。您可以使用 weather 函数测试以查看 cfData 中是否存在 structKeyExists()。下面的代码为我运行没有错误:

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

关于json - ColdFusion 解析 JSON,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35021811/

10-08 21:41