规范化 JSON 文件

2022-09-01 11:04:03

我有一堆自动生成的JSON文件,我想将它们存储在版本控制中。问题是,每次序列化文件时,属性都会以不同的顺序出现,因此很难知道文件是否真的发生了变化和/或真正的差异是什么。

有谁知道现有的开源工具可以执行此任务?

如果做不到这一点,有没有人知道一个带有解析器和生成器的JSON库,可以配置为输出具有(例如)词法顺序属性的“漂亮”JSON?(Java或Ruby库将是理想的,但也欢迎其他潜在客户。


答案 1

Python的JSON模块在其他程序中非常有用:

generate_json | python -mjson.tool > canonical.json

答案 2

如果您愿意通过致电来经历一些开销

gson.toJson(canonicalize(gson.toJsonTree(obj)));

然后你可以做这样的事情:

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;
  }
}