Variable name starting with @ causes error: Invalid token @ found on line X at column Y

Viewed 272

I am trying to format a ColdFusion page with data from the National Weather Service API (NOAA). Using the following ColdFusion code I am able to dump the data.

<cfhttp url="https://api.weather.gov/alerts/active/zone/ANZ335" result="weather">
<cfhttpparam name="accept" type="header" value="application/ld+json">
</cfhttp>
<cfset alerts = deserializeJSON(#weather.filecontent#) /> 

In the dump, I can XML data that uses a "@" character to name the nodes. Dump of XML Data

However, ColdFusion does not like the @ sign when you try to output the values. For example:

#arraylen(alerts.@graph)#

Causes an "Invalid token @ found on line X..." error.

Any ideas on how I can get by this issue?

1 Answers

When using dot notation, variable names must adhere to CF's variable naming rules. In particular:

A variable name must begin with a letter, underscore, or Unicode currency symbol....

For structure keys with invalid variable names, use associative array notation:

structName["keyNameInQuotes"] 

... or more specifically:

 alerts["@graph"]

As @Shawn mentioned in the comments, you can also mix dot notation with associative array notation. So these are valid as well:

variables.alerts["@graphs"]
variables["alerts"]["@graphs"]
Related