ColdFusion 11 读取多级 JSON 文件

ColdFusion 11 reading mulit-level JSON file

我有一个正常运行的 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 文件,它有更多的层次,但我不知道如何将相同的数据处理到新的层次。

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

在 JSON 中,数组用方括号 [] 括起来,结构用花括号 {} 括起来。

反序列化调用 JSON 会为您完成所有工作。将您的第二个文件作为包含结构数组的结构数组。

因此,如果您想要每个数组中的第一个元素:

mydoc[1].self_study[1].categories[1]
mydoc[1].self_study[1].initiative

显然,您可以在数组上使用所有数组操作,在结构上使用结构操作。希望这些信息足以让您继续前进。