Page 1 of 1

is there a way to sort json objects?

Posted: Thu Jul 15, 2010 3:23 pm
by wolph42
a quick question:
is there a(n easy) way to sort json objects?
I know that json.sort does arrays, but is there also something for objects?

Re: is there a way to sort json objects?

Posted: Thu Jul 15, 2010 3:52 pm
by plothos
Nope, I don't think so.
You could maybe make a udf, though.
use json.fields() to get a list, sort the list and create a new object by calling the original values in that order. I'm assuming the order of the object is reflective of the order the fields are added, though this may not be true.

Re: is there a way to sort json objects?

Posted: Thu Jul 15, 2010 4:24 pm
by biodude
There's an example on the wiki of a UDF for [wiki]Sorting Nested JSON Objects[/wiki] (by sub-fields), if that's what you're looking for.
Look under [wiki]JSON Sorting[/wiki] for the code.

Re: is there a way to sort json objects?

Posted: Thu Jul 15, 2010 4:57 pm
by aliasmask
I'm not sure and you may want to test, but I think the order remains the same once you set a keyword. So, if your object doesn't change too much, adding and removing keys, then you could use json.fields and return it as a json array. Then use json.sort on the array. Use a foreach to write a new obj in your needed order and replace the old obj with the new obj. Then it will remain sorted and you won't have to keep using json.fields and json.sort. You can put the obj in to foreach and it should be in the correct order.

Re: is there a way to sort json objects?

Posted: Thu Jul 15, 2010 5:23 pm
by wolph42
thnx for the suggestions. I feared that there was no easy way, but creating a udf shouldn't be too hard. Its only the fields I wanted sorted not the nested objects.

Re: is there a way to sort json objects?

Posted: Thu Jul 15, 2010 8:39 pm
by prestidigitator
I don't believe there are any guarantees, so even if you manage to find some hack to get it to work now, there may be a point where it stops working in the future. I'd look at WHY you want to sort them, and that might give you a clue as to where and how to do it. You may be able to do it at the point where you are retrieving and using the values from the object, or you may want to add some kind of special field that holds (a cached array of) the sorted names of the other fields.

Re: is there a way to sort json objects?

Posted: Fri Jul 16, 2010 3:37 am
by wolph42
i need it because I regularly output the fields to screen, currently i just solved it by listSort(json.fields(etc)) however as changes are much less frequent than screenupdates its faster if they stored sorted, hence my question. Though a sotred in chache is also an interesting idea.