我有一个正常运行的ColdFusion 11站点,它引入一个JSON文件并反序列化它,我能够输出内容。有效的JSON看起来像这样:
[
{"body":"some text goes here",
"link":"a link is here",
"name":"name of product goes here",
"language":"language goes here",
"tags":["tag1","tag2","tag3","tag4"],
"initiative":"initiative content goes here",
"start_date":"start date goes here",
"categories":["cat1","cat2","cat3"]
}
现在他们给了我一个新的JSON文件,它有更多的级别,我无法弄清楚如何降低到同一数据的新级别。
NEW JSON
[
{
"self_study":
[
{
"categories":["Cat1","Cat2"],
"link":"some link",
"initiative":"initiative content goes here",
"language":"language goes here",
"name":"name of product",
"tags":["tag1","tag2","tag3","tag4"],
"body":"some text goes here"
}
],
"scheduled":
[
{
"categories":["Cat1","Cat2"],
"link":"some link",
"initiative":"initiative content goes here",
"language":"language goes here",
"name":"name of product",
"tags":["tag1","tag2","tag3","tag4"],
"body":"some text goes here"
}
]
}
]
使用第一个JSON文件,我可以使用CFLOOP循环访问数据
<cffile action="read" file="#ExpandPath("./MoocJson.json")#" variable="myxml">
<cfset mydoc = deserializedJSON(myxml)>
<cfdump var="#mydoc#"> <!--- this dumps out the JSON in Array format --->
<cfoutput> My Doc Length = #arraylen(mydoc)#</cfoutput>
<!--- Loop through Array of mydoc and out put content --->
<cfoutput>
<cfloop from="1" to="#arrayLen(mydoc)#" index="i">
<cfset Course = mydoc[i]>
#Course.Name# <br>
#Course.body# <br>
#Course.language# <br>
#Course.link# <br>
#Course.initiative# <br>
#Course.start_date# <br>
#ArrayToList(Course.tags)# <br>
#ArrayToList(Course.categories)# <br>
</cfloop>
</cfoutput>
<!--- End of Code --->
对于CFDUMP,我得到了这个结构:
Array(1)
Struct(scheduled)
Array(1)
Struct(my data)
Struct(self_study)
Array(1)
Struct(my data)
关于如何向下浏览多级JSON的任何想法?
答案 0 :(得分:2)
在JSON数组中,方括号[]和花括号{}中的结构。
对JSON进行反序列化的调用会为您完成所有工作。将第二个文件作为包含结构数组的结构数组。
所以如果你想要每个数组的第一个元素:
mydoc[1].self_study[1].categories[1]
mydoc[1].self_study[1].initiative
显然,您可以使用数组上的所有数组操作和结构上的结构操作。希望这足以让你前进。