Hi
omarge94,
There's a problem with this sort that it considers the numeric value as a string (not numeric).
That's what I had in view saying 'this' and 'particular' case...
I will be migrating to
coco's JSON lib, how could I use sort separately, without editing the library
JSON.Load() because I will need to reuse it without the sort functionality.
I personally don't use this library even though I suggested using it. But
as per the method description, the library can receive a reviver/ a replacer on loading/dumping respectively - that is, the parsing/stringification process of dump/load method can be altered before returning:
Code: Select all
SETTINGS_FILE := A_ScriptDir . "\sample.json"
output := JSON.Load(file:=FileOpen(SETTINGS_FILE, "r", "utf-8").read(), Func("myReviver")), file.close()
myReviver(k, v) {
; return value as is if you don't want to alter it
; return [value][1] ; for numeric values, preserve internally cached number
}
Here's an other solution which operate once the object is returned instead (note: it handle only integers):
Code: Select all
global sample ; assuming the sample json is loaded and save in 'sample' variable
sort(who, sortBy, ByRef obj) {
(p := (sortBy == "last_date_of_contribution" ? "_" : "")) ; last_date_of_contribution value is to large and should be converted to a string for this to work
for _, var in (who:=sample[who]), obj := []
obj[ p . var[sortBy] ] := a_index
}
for each, characteristic in ["last_date_of_contribution", "id", "score"]
{
sort("students", characteristic, myObj)
for k, v in myObj
MsgBox % characteristic . A_Space . k . "," . sample.students[v].name
}
function() {
static __ := function()
global sample :=
(LTrim Join
{
"students": [
{
"name": "Aubrey",
"id": "2",
"score": "93",
"last_date_of_contribution": 1488192196481
},
{
"name": "Lillian",
"id": "5",
"score": "11123",
"last_date_of_contribution": 1491491812832
},
{
"name": "Hannah",
"id": "4",
"score": "2345",
"last_date_of_contribution": 1488037180604
},
{
"name": "Alexis",
"id": "1",
"score": "563",
"last_date_of_contribution": 1488036780822
},
{
"name": "Charlotte",
"id": "3",
"score": "6311",
"last_date_of_contribution": 1488231252924
}
],
"teachers": [
{
"name": "Natalie",
"id": "21695",
"last_date_of_contribution": 1503710683888
},
{
"name": "Olivia",
"id": "19745",
"last_date_of_contribution": 1484406671159
},
{
"name": "Isabella",
"id": "18674",
"last_date_of_contribution": 1471546107140
},
{
"name": "Sophia",
"id": "17169",
"last_date_of_contribution": 1481488109129
},
{
"name": "Emma",
"id": "14051",
"last_date_of_contribution": 1465785844146
}
]
}
)
}
- Btw, it's your own json structure, I suggest you review it to make it more compliant with your specific goals.
- Heres' another link you might find intersesting:
Sorting an associative array by values
- Alternatively, you can build a list and and use the built-in
Sort command.
Hope this helps
[EDIT]Once again sorry for the late reply, I simply missed yours.