One of the real powers of ColdFusion is the ability to work with various types of data, but I find that it is often difficult to get started with something other than cfquery. I hope this helps others get started faster than I did. This is really my first foray into working with JSON for something other than charting, so if you see things that I should do differently I invite constructive comments.
To set the stage, I am working on a tools that pulls data from the USAJOBS API and it is visible in the demo area. This is a variation of a tool that I am building in my day job and I thought I would use it here for demonstration purposes.
Step 1. Get the Data
For the purposes of this post, I will be working with remote data, but you can work with local JSON files or generate JSON from a database. The first step is to get the data and API publishers will explain if there are security controls. Â The data set in this portion of the demo is open and does not require an API key. Â What I need is a way to populate a dropdown list with organizations. Â The URL for the data is https://data.usajobs.gov/api/codelist/agencysubelements. Using a cfhttp request I can easily retrieve the data:
Step 2. Making it Usable
Once you have the data you need to put it in a workable format and ColdFusion makes this really easy using deserialize JSON. Â This will take your JSON data and parse it into an array. Don’t forget, as you saw in the dump above, the results you are after are in the data assigned to filecontent within the “orgs” structure.
I have created a component to do this:
Now that your data is in an array it should be fairly straightforward to work with Â – assuming you are familiar with working with arrays.
As you see, with this data you end up with an array in a structure within an array. In all honesty, it took me a minute or ten to figure this out, and assuming I am doing it the easiest way possible, you just need to loop over the array to get the data, so you can loop over the second array.
Step 3. Using it for a Form
This is actually a lot more data than I need for my form and there is a property called isDisabled which indicates inactive values that I do not want to display to the end user. Â In this demo I just want the two letter organizations and to hide any disabled values and a simple solves the problem. Here is the code for the form field:
The last thing I need to do is sort the data by the organization name data.value, but so far I haven’t figured out how to do that. Â Once I figure it out, I will add that to this article.
For now, you can view the full demoÂ as it stands right now.
Note: Since the examples rely on external data, performance can be impacted by their maintenance schedule or network issues.