komorebi / recipe - json - structural signature

Created Fri, 31 May 2024 19:27:04 -0700 Modified Sat, 01 Jun 2024 07:34:18 +0000
176 Words

Take this sample from https://json.org/example.html

cat foo.json

{
  "glossary": {
    "GlossDiv": {
      "GlossList": {
        "GlossEntry": {
          "Abbrev": "ISO 8879:1986",
          "Acronym": "SGML",
          "GlossDef": {
            "GlossSeeAlso": [
              "GML",
              "XML"
            ],
            "para": "A meta-markup language, used to create markup languages such as DocBook."
          },
          "GlossSee": "markup",
          "GlossTerm": "Standard Generalized Markup Language",
          "ID": "SGML",
          "SortAs": "SGML"
        }
      },
      "title": "S"
    },
    "title": "example glossary"
  }
}

Instead of using JQ or higher-level programming language to recurse and nullify values, you can quickly do the following:

  • sort keys-value pairs with JQ
  • flatten the JSON with GRON
  • SED the value portion of the flattened JSON
  • unflatten the JSON with GRON
  • pretty the JSON with JQ

jq --sort-keys '.' foo.json | gron | sed -E 's~= ".+$~= "";~' | gron -u | jq

{
  "glossary": {
    "GlossDiv": {
      "GlossList": {
        "GlossEntry": {
          "Abbrev": "",
          "Acronym": "",
          "GlossDef": {
            "GlossSeeAlso": [
              "",
              ""
            ],
            "para": ""
          },
          "GlossSee": "",
          "GlossTerm": "",
          "ID": "",
          "SortAs": ""
        }
      },
      "title": ""
    },
    "title": ""
  }
}

You can then use this structure sig in a diff.