I have the following constract when parsing .json ...
# cfml-beginners
e
I have the following constract when parsing .json file:
<cfset line_items = jsonData.order.line_items>
<cfloop array="#line_items#" index="line_item">
<cfset line_item_sku = #line_item.sku#>
</cfloop>
This time, for some reason "sku" is not defined (Element SKU is undefined in LINE_ITEM.). Question: how do I make sku = 'XX' if it's not defined. I've tried Elvis notation, but without success (<cfset line_item_sku = #line_item.sku#?:"XX">)
t
<cfset line_item_sku = isDefined("line_item.sku") ? line_item.sku : "xx">
🙌 1
m
I would use use
structKeyExists()
to check if it exists in the struct. BTW, you don't need the pounds (
#...#
) around the variable when you are setting
line_item_sku
.
d
You can use a safe navigation operator. This tries to use the json value and if it doesn't exist will return your default value
<cfset line_item_sku = line_item?.sku ?: 'XX'>
âž• 3
e
Thank you all for your replies. Question about # signs. I thought I need them because I am setting line_item_sku to then "value" of line_item.sku, so I'd need inclose it into #s.
m
If you're not within a string literal, you don't need it.
<cfset mystring = "My name is #name#" />
<cfset myOtherString = aVariable />
e
Thanks again. I can only imagine how many of those I need to remove :-)