Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using JSON Data with Coldfusion

I've worked with JSON data in the past - mainly 'fudging' my way to a solution, and not really understanding why or how things work. I've come across an issue where the data being returned looks somewhat different to what I've seen before, and I can't find any examples that match it.

Here's an example of the data returned (via an API);

{"domain.co.uk":{"status":"available","classkey":"thirdleveldotuk"},"domain.net":{"status":"available","classkey":"dotnet"},"domain.com":{"status":"available","classkey":"domcno"}}

On my front-end, I need to return something like this -

  • domain.co.uk - available
  • domain.net - available
  • domain.com - available

Because the 'domain.com' etc value will always change, I can't map the names as I usually would (although it will always be 3 'rows' returned)

I've checked every CF Book I own, and read the online CF Docs, but I'm totally at a loss as to where to even start with this one!

Pointers much appreciated!

like image 855
Lee Avatar asked Dec 01 '22 19:12

Lee


1 Answers

If you run this with deserializeJSON(data), you'll see that you just end up with structures with nested structures. So, you can loop through your struct, grab the keys and then grab that key's status. In JSON terms, your JSON object has nested objects.

<cfset data = deserializeJSON(apiData) />
<cfset formattedData = [] />
<cfset tmp = {} />

<cfloop collection=#data# item="domain">
    <cfset tmp.domain = domain />
    <cfset tmp.status = data[domain]["status"] />
    <cfset arrayAppend(formattedData,duplicate(tmp)) />
</cfloop>

<cfdump var=#formattedData# />
like image 178
J.T. Avatar answered Dec 23 '22 12:12

J.T.