Question

I've been converting CF structs etc to JSON for a while now, and all good. Coldbox in particular makes this really easy.

However, I am currently working with a jQuery Datatable and need to pass it jSON in the format below.

I am starting with an array of objects.

I only want certain properties in each object to go into the final JSON String.

I'm running around in circles and possibly totally overcomplicating converting my data into this format JSON. Can anyone help, or suggest an easy way I might be able to do this..

Also worth mentioning I am building this in coldbox. Coldfusion 9.

{ "aaData": [ [ "Test1", "test@test1", "444444444", "<i class=''icon-pencil icon-large'' data-id=''s1''></i>" ],[ "Test2", "test@test2", "555555555", "<i class=''icon-pencil icon-large'' data-id=''s2''></i>" ],[ "Test3", "test@test3", "666666666", "<i class=''icon-pencil icon-large'' data-id=''s3''></i>" ] ]}

Many Thanks!

======================================================

Here is the code that game we what I needed:

var dataStruct = structNew();
var dataArray = arrayNew(1);
var subsArray = arrayNew(1);
var subs = prc.org.getSubscribers();

for (i=1; i<=arrayLen(subs); i++){
    arrayAppend(subsArray,"#subs[i].getName()#");
    arrayAppend(subsArray,"#subs[i].getEmail()#");
    arrayAppend(subsArray,"#subs[i].getMobile()#");
    arrayAppend(subsArray,"<i class='icon-pencil icon-large' data-id='s#subs[i].getID()#'></i>");
    arrayAppend(dataArray,subsArray);
    arrayClear(subsArray);
};
structInsert(dataStruct,'aaData',dataArray);    
event.renderData('json',dataStruct);
Was it helpful?

Solution

OK, so you've got an array which has objects, and the objects contain all the properties which you need to end up in this JSONed array, yeah?

So do this:

create a new array
loop over the array of objects
    create a struct
    put all the values from each object you need to go into the JSON; be mindful to use associative array notation when setting the keys, to perserve the case of the keys
    append the struct to the new array
/loop
serializeJson the new array

I don't think there's any simpler way of doing it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top