OData Syntax and JSON

The last html web resource I wrote seemed to be another routine coding activity.  This was a simple graphical indicator to display a light based on a value in a CRM form, and a simple OData query to fetch a single value.

This time I decided to use the following syntax:


The Odata query worked as expected but the web resource was not.  Nothing was displayed and no error was generated.

After several hours of research and debugging, I found out that the JSON string that was generated had the following format:


This was a little bit different from what my standard parsing routine expected.  Basically, the idea was to traverse an array called “results” using this construct:

var retrievedData = new XMLHttpRequest();

retrievedData.open(“GET”, url, false);

retrievedData.setRequestHeader(“Accept”, “application/json”);

retrievedData.setRequestHeader(“Content-Type”, “application/json; charset=utf-8”);

retrievedData.onreadystatechange = function () { retrieveReqCallBack(this, destination); };


var fetchedData = JSON.parse(retrievedData.responseText).d;

for (var i = 0; i < fetchedData.results.length; i++) {



Looking at old web resources that fetched multiple records, the JSON string returned was like this:


So, I had a smoking gun and then the fix was relatively easy. I just needed to access the attributes of the returned (single-record) dataset directly:

var dateStart = fetchedData.myAttribute;


But I wasn’t happy just finding a fix to the problem.  I needed to find the root of the problem, why was the JSON string different?

The answer was in the OData syntax used.  In previous web resources I had used “filter”:

http://<servername>/xrmservices/2011/OrganizationData.svc/<Entity>Set?$filter=<key_name>/Id eq guid'{ <guid_value> }’&$select=<list_of_fields>

This syntax will fetch the same single record but it will use the equivalent to RetrieveMultiple in the SDK, which automatically wraps the fetched results in an array called “results”.

So, keep that in mind the next time you use OData, that the syntax you choose may have an impact on how the returned dataset needs to be parsed.



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: