I’ve been having trouble figuring this out so I figured i’d ask here. I’m using Ruby 1.8.7 and RoR 1.2.6. I have my controller rendering this JSON:
{
"form_id": "1",
"form_structure": {
"3": {
"answer_required": "undefined",
"title": "This is a radio group, right?",
"cssClass": "radio",
"values": {
"4": {
"value": "Yes",
"baseline": "undefined"
},
"5": {
"value": "No",
"baseline": "undefined"
},
"7": {
"value": "Maybe",
"baseline": "undefined"
},
"20": {
"value": "Test",
"baseline": "undefined"
}
}
}
}
}
As you can see, the options under “values” are ordered by the ID from the table. Looks perfect in JSON. When I use JSON.parse on it, everything under “values” get’s all out of whack and it returns this:
{
"form_id"=>"1",
"form_structure"=>{
"3"=>{
"title"=>"This is a radio group, right?",
"cssClass"=>"radio",
"answer_required"=>"undefined",
"values"=>{
"7"=>{
"baseline"=>"undefined",
"value"=>"Maybe"
},
"20"=>{
"baseline"=>"undefined",
"value"=>"Test"
},
"4"=>{
"baseline"=>"undefined",
"value"=>"Yes"
},
"5"=>{
"baseline"=>"undefined",
"value"=>"No"
}
}
}
}
}
This code is used in a formbuilder that I’m making, and it wouldn’t really be nice if the form elements that a person builds don’t show up in the correct order that they built them in. Anyone have insights on how I can keep the ordering or reorder them as I output or right before then?
Here you go:
This will sort the hash based on the integer value of the keys in the values hash and put the sorted hash back in the larger hash.
If you need to keep it all still hashes use this: