Canonicalizing JSON files
Python's JSON module is very usable from other programs:
generate_json | python -mjson.tool > canonical.json
If you're willing to go through a bit of overhead by calling
gson.toJson(canonicalize(gson.toJsonTree(obj)));
Then you can do something like this:
protected static JsonElement canonicalize(JsonElement src) { if (src instanceof JsonArray) { // Canonicalize each element of the array JsonArray srcArray = (JsonArray)src; JsonArray result = new JsonArray(); for (int i = 0; i < srcArray.size(); i++) { result.add(canonicalize(srcArray.get(i))); } return result; } else if (src instanceof JsonObject) { // Sort the attributes by name, and the canonicalize each element of the object JsonObject srcObject = (JsonObject)src; JsonObject result = new JsonObject(); TreeSet<String> attributes = new TreeSet<>(); for (Map.Entry<String, JsonElement> entry : srcObject.entrySet()) { attributes.add(entry.getKey()); } for (String attribute : attributes) { result.add(attribute, canonicalize(srcObject.get(attribute))); } return result; } else { return src; }}
This is supported in Jackson:
@JsonPropertyOrder(alphabetic=true)