1

deserialized json -> coldfusion struct with arrays

Here is Google calendar data retrieved from https://www.googleapis.com/calendar/v3/users/me/calendarList.

The response is in JSON, so I used the ColdFusion method deserializeJson to turn it into a CFML structure.

I cannot figure out the syntax to loop over this data. You'll see that within the CFML struct, 'items' is an array of calendars returned from Google, and every attempt to access the array within the struct generates a Java string conversion error or a syntax error, likely because I can't get the syntax correct.

Any help is very appreciated, thanks very much

peter jalton
  • 109
  • 1
  • 9
  • 5
    Can you post what have you tried so far and also the JSON response so that it will be easier to test the solution. – Keshav jha Apr 12 '16 at 14:44
  • 1
    Best place to start is [cfloop collection](http://help.adobe.com/en_US/ColdFusion/9.0/Developing/WSc3ff6d0ea77859461172e0811cbec09f0b-7fdb.html) and [cfloop array](http://help.adobe.com/en_US/ColdFusion/9.0/CFMLRef/WSc3ff6d0ea77859461172e0811cbec22c24-71a7.html). Also, check [this](http://stackoverflow.com/questions/19719506/coldfusion-how-to-loop-through-an-array-of-structure-and-print-out-dynamically) example. – Abhishekh Gupta Apr 12 '16 at 15:37

1 Answers1

9

Some trial and error will help - you are already on your way. The root object you dumped out already but we'll do it here to represent the object you dumped out as "obj":

<cfset obj = deserializejson(googleCal)>

The first level is a struct so you would address them as follows:

#obj.etag#  // this is a string

items contains an array. So you have items[1-n] ... however many are in the array. This code would set myArrayObj as an array with 3 items (based on the dump above).

<cfset myArrayObj = obj.items>

You can verify using isArray:

#isArray(myArrayObj)#

Each array member contains a struct in turn so you can output:

#myArrayObj[1].accessRole#  // this would be a string

... And so on. Make a note that index item 3 in the array is a blank struct so you need to "check" to see if the struct is empty before you work with it's keys. Investigate "structKeyExists()" for that purpose.

If you want to deal with each of the "items" in a loop (a pretty typical choice) you would simply do a cfscript loop or cfloop using array as in:

<cfloop array="#myArrayObj#" index="i">

    <cfif structKeyExists(myArrayOb[i], "accessRole")>
         #myArrayObj[i].accessRole#
    </cfif>
</cfloop>

Hope this helps. Good luck!

Mark A Kruger
  • 7,183
  • 20
  • 21