1

I'm working with a web API, which is returning the following data (this is a cfdump of the cfhttp.filecontent);

{"id":"xxx","service1":["xxx"],"service2":["xxx"]}

I need to be able to read this and determine if a service is on the list. For example,

<cfscript>
pdata = deserializeJSON(cfhttp.FileContent);
</cfscript>

<cfif IsDefined(pdata.service1)>Do something</cfif>

However, I'm receiving an error with the above code. I've only recently started working with JSON, and so far I've had reasonable success - but I'm stuck with this!

Any pointers much appreciated!

2
  • 1
    Fortunately this problem was easier to spot than others. But in future, always post the error message. It will take far less time to get an answer when people do not have to "guess" what the problem is.. Commented Oct 5, 2012 at 21:48
  • 1
    It's recommended practice to use StructKeyExists instead of IsDefined. <cfif StructKeyExists(pdata, "service1")>...</cfif> Commented Oct 8, 2012 at 9:27

1 Answer 1

2

It should be IsDefined("pdata.service1")

With isDefined() CF needs to know the name of the variable you are asking about. A name is a string, so you pass in a string.

I found it to be a little counter-intuitive at first, but JasonDean put it into perspective in the comments.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks! That's a sure sign I've been looking at this too long, you are indeed correct - I was missing the quotations.
No worries, don't forget to accept. :) It happens to me alot, CF error handling is pretty descriptive most of the time and can tell you what's wrong.
I don't think it is counter-intuitive at all. With isDefined() CF needs to know the name of the variable you are asking about. A name is a string, so you pass in a string. How could it expect a variable to be passed in? If the variable doesn't exist, how can it be passed in? It's all in how you think about it.
@JasonDean Thanks, I never thought of it that way but it makes sense. I wasn't formally trained in CF, just thrown into the deep end. I added that information to the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.