How can I sort JSON by ID?

You could submit a proposed change – processing/core/src/processing/data/JSONArray.java at master · processing/processing · GitHub

Or if you don’t want a wrapper function, you can extend JSONArray yourself. Here is an example based on the JSONArray reference example, but using a simple JSONObject id String comparator as in our discussion.

/**
 * JSONArraySorting
 * 2019-12 Extend JSONArray and add a custom sort
 */

// begin with the reference JSONArray example:
// https://processing.org/reference/JSONArray.html

import java.util.Collections;  // added
import java.util.Comparator;   // added 

String[] species = { "Capra hircus", "Panthera pardus", "Equus zebra" };
String[] names = { "Goat", "Leopard", "Zebra" };
JSONArraySortable values;            // change to extended class

void setup() {
  values = new JSONArraySortable();  // change to extended class
  for (int i = 0; i < species.length; i++) {
    JSONObject animal = new JSONObject();
    animal.setString("id", ""+(species.length-i));  // number w/Strings, 3-2-1
    animal.setString("species", species[i]);
    animal.setString("name", names[i]);
    values.setJSONObject(i, animal);
  }
  saveJSONArray(values, "data/new.json");   // saves 3-2-1
 
  // now sort the array by its object "id" keys and save it again
  values.sort();
  saveJSONArray(values, "data/new2.json");  // saves 1-2-3
  
}

class JSONArraySortable extends JSONArray {
  
  // pairwise comparison logic for sort is in the Comparator
  class JSONComparator implements Comparator<JSONObject> {
    @Override
      public int compare (JSONObject a, JSONObject b) {
      return Long.compare(Long.valueOf(a.getString("id")), Long.valueOf(b.getString("id")));
    }
  }
  
  // utility -- sort will need to get all objects from private ArrayList
  ArrayList<JSONObject> getAll() {
    ArrayList<JSONObject> myobjs = new ArrayList<JSONObject>();
    for (int i=0; i<this.size(); i++) {
      myobjs.add((JSONObject)this.get(i));
    }
    return myobjs;
  }
  
  // utility -- sort will need to clear all objects from private ArrayList
  public void clear() {
    for (int i=this.size()-1; i>=0; i--) {
      this.remove(i);
    }
  }
  
  // sort by getting all objects, sorting with comparator, clearing, and appending
  public void sort() {
    ArrayList<JSONObject> myobjs = this.getAll();
    Collections.sort(myobjs, new JSONComparator());
    this.clear();
    for (int i=0; i<myobjs.size(); i++) {
      this.append(myobjs.get(i));
    }
  }
}
1 Like