RPTools

From MapToolDoc

json.sort

json.sort() Function

Introduced in version 1.3b51

Used to sort JSON arrays. If the array contains only numbers, they are sorted numerical, otherwise the values are sorted as strings alphabetically.

Usage

  1. json.sort(array)
  1. json.sort(array, direction)

If you have a JSON Array that contains JSON Objects

  1. json.sort(array, direction, key1, ..., keyN)

Parameters

  • array - The JSON array to sort.
  • direction - Defaults to "ascending", acceptable values:
    • "ascending"
    • "descending"
    • "ascend"
    • "descend"
    • "asc"
    • "desc"
    • "a"
    • "d"
  • key1, ..., keyN - The keys in the JSON Objects contained within the JSON Array used for sorting. All JSON Objects must contain these fields.

Examples

Sorting a JSON Array containing numbers.

  1. [json.sort("[1,4,5,6,2,1,9,20,1]")]

Produces [1,1,1,2,4,5,6,9,20]

Sorting a JSON Array containing strings.

  1. [json.sort("['Hero', 'Dragon', 'Elf', 'Wolf', 'Mage', 'Eagle', 'Troll']")]

Produces ["Dragon","Eagle","Elf","Hero","Mage","Troll","Wolf"]


Sorting a mixture of numbers and strings (all will be treated as string).

  1. [json.sort("['Hero', 3, 'Elf', 'Wolf', 100, 'Eagle', 'Troll']")]

Produces [100,3,"Eagle","Elf","Hero","Troll","Wolf"]


Sorting objects by a single string key

  1. [h:vals = '[ {name:"Hero", HP:10}, 
  2.              {name:"Wolf", HP:5}, 
  3.              {name:"Mage", HP:20}, 
  4.              {name:"Troll", HP:15}, 
  5.              {name:"Eagle", HP:5} ]'] 
  6. [json.sort(vals, "a", "name")]

Produces

[{"name":"Eagle","HP":5},{"name":"Hero","HP":10},{"name":"Mage","HP":20},{"name":"Troll","HP":15},{"name":"Wolf","HP":5}]

Sorting objects by a single numeric key

  1. [h:vals = '[ {name:"Hero", HP:10}, 
  2.              {name:"Wolf", HP:5}, 
  3.              {name:"Mage", HP:20}, 
  4.              {name:"Troll", HP:15}, 
  5.              {name:"Eagle", HP:5} ]'] 
  6. [json.sort(vals, "a", "HP")]

Produces

[{"name":"Wolf","HP":5},{"name":"Eagle","HP":5},{"name":"Hero","HP":10},{"name":"Troll","HP":15},{"name":"Mage","HP":20}]


Sorting objects by a two keys, first HP then Name.

  1. [h:vals = '[ {name:"Hero", HP:10}, 
  2.              {name:"Wolf", HP:5}, 
  3.              {name:"Mage", HP:20}, 
  4.              {name:"Troll", HP:15}, 
  5.              {name:"Eagle", HP:5} ]'] 
  6. [json.sort(vals, "a", "HP", "name")]

Produces

[{"name":"Eagle","HP":5},{"name":"Wolf","HP":5},{"name":"Hero","HP":10},{"name":"Troll","HP":15},{"name":"Mage","HP":20}]