如何解析 CF 结构
How to parse CF struct
我正在从 API 调用中收到一个 JSON 字符串并将其反序列化。但是,我在尝试访问嵌套结构中的某些键时遇到问题:
当我执行以下操作时,我得到了所有外键的列表,但我不确定如何从那里继续。
<cfset jsonData = deserializeJSON(httpResp.fileContent) />
<cfloop collection="#jsonData#" item="i">
<cfoutput>
<br>#i#
</cfoutput>
</cfloop>
最终,我需要在 items
元素中获取 street
数组数据,barcode
和 sku
。我尝试使用点符号,但收到错误消息:
You have attempted to dereference a scalar variable of type class
java.lang.String as a structure with members.
该错误仅表示您的路径错误,并且代码将某些内容视为实际上只是字符串的结构。虽然数据结构可能与 不同,但如何访问值的概念是相同的。您只需要找到所需键的正确路径。请记住,JSON 是一种非常简单的格式。它本质上由两种对象类型组成:结构和数组。因此访问任何元素只需要正确的键名系列 and/or 数组位置。
通常 结构键可以用dot-notation 访问。但是,如果键名不符合 CF's variable naming rules, you'll need to use associative array notation(或两者的混合):
someStructure.path.to.keyname <== dot-notation
someStructure["path"]["to"]["keyname"] <=== associative array notation
someStructure.path["to"].keyname <=== mix of both
街道元素
访问此元素非常简单。键名是一个有效的变量名,所以可以用dot-notation访问。由于它的 value 是一个数组,如果您只想要该数组中的 specific 元素,您还需要提供一个位置:
addresses.customer.street[1] <=== first element
addresses.customer.street[2] <=== second element
条码元素
同样,barcode
是嵌套结构中的键。但是,有两个区别。某些父键名称包含无效字符(破折号),因此您无法使用 dot-notation 访问 "barcode"。此外,一些父键似乎是动态的:
items.{dynamic_uuid}.metadata.barcode
由于您无法提前知道这些,访问它们的唯一方法是动态循环访问父结构 (items
) 键并使用关联符号:
<!--- demo structure --->
<cfset props = {items : {"#createUUID()#" : {metadata : {barcode :"759855743302"}} } }>
<cfloop collection="#props.items#" item="dynamicKey">
<cfoutput>
barcode = #props.items[dynamicKey].metadata.barcode#
</cfoutput>
</cfloop>
我正在从 API 调用中收到一个 JSON 字符串并将其反序列化。但是,我在尝试访问嵌套结构中的某些键时遇到问题:
当我执行以下操作时,我得到了所有外键的列表,但我不确定如何从那里继续。
<cfset jsonData = deserializeJSON(httpResp.fileContent) />
<cfloop collection="#jsonData#" item="i">
<cfoutput>
<br>#i#
</cfoutput>
</cfloop>
最终,我需要在 items
元素中获取 street
数组数据,barcode
和 sku
。我尝试使用点符号,但收到错误消息:
You have attempted to dereference a scalar variable of type class java.lang.String as a structure with members.
该错误仅表示您的路径错误,并且代码将某些内容视为实际上只是字符串的结构。虽然数据结构可能与
通常 结构键可以用dot-notation 访问。但是,如果键名不符合 CF's variable naming rules, you'll need to use associative array notation(或两者的混合):
someStructure.path.to.keyname <== dot-notation
someStructure["path"]["to"]["keyname"] <=== associative array notation
someStructure.path["to"].keyname <=== mix of both
街道元素
访问此元素非常简单。键名是一个有效的变量名,所以可以用dot-notation访问。由于它的 value 是一个数组,如果您只想要该数组中的 specific 元素,您还需要提供一个位置:
addresses.customer.street[1] <=== first element
addresses.customer.street[2] <=== second element
条码元素
同样,barcode
是嵌套结构中的键。但是,有两个区别。某些父键名称包含无效字符(破折号),因此您无法使用 dot-notation 访问 "barcode"。此外,一些父键似乎是动态的:
items.{dynamic_uuid}.metadata.barcode
由于您无法提前知道这些,访问它们的唯一方法是动态循环访问父结构 (items
) 键并使用关联符号:
<!--- demo structure --->
<cfset props = {items : {"#createUUID()#" : {metadata : {barcode :"759855743302"}} } }>
<cfloop collection="#props.items#" item="dynamicKey">
<cfoutput>
barcode = #props.items[dynamicKey].metadata.barcode#
</cfoutput>
</cfloop>