Skip to content

Instantly share code, notes, and snippets.

@barthap
Created July 5, 2022 21:57
Show Gist options
  • Save barthap/90eb52f5c7fb31156f27f46d9d1af954 to your computer and use it in GitHub Desktop.
Save barthap/90eb52f5c7fb31156f27f46d9d1af954 to your computer and use it in GitHub Desktop.
Pretty git diff for minified JSON

How to see pretty git diff for minified JSON files

Problem: You are about to commit a change in minified, one-liner JSON file and want to see the diff.

Requirements:

  • Node.js - if you're not a JS guy, you'll need to write the pretty_json file (see below) in language of your choice
  • (Optional) colordiff - or any other tool to colorize your diffs

Here's my unix/mac solution:

  1. Copy the pretty_json file to some directory that is in your PATH.
  2. If you're a vim enthusiast, copy the vimdiff_json to the same directory as the pretty_json file.
  3. Otherwise, copy the diff_json to the same directory. Or why not copy both?
  4. Run the following commands:
    cd <that_directory_you_copied_files_to>
    chmod +x pretty_json diff_json vimdiff_json
    git config --global difftool.diff_json.cmd "diff_json \$LOCAL \$REMOTE"
    git config --global difftool.vimdiff_json.cmd "vimdiff_json \$LOCAL \$REMOTE"
    git config --global difftool.prompt false
  5. You're probably all set (unless I missed something)

Now you can git diff your json file this way:

git difftool ./relative_path/to.json --tool vimdiff_json

# or replace vimdiff_json with diff_json above if you're not into vim

Important note: To exit vim diff, press Esc, then type qa! and press Enter.

#!/usr/bin/env bash
SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
# NOTE: Pure 'diff' command is ugly
# You can replace diff with colordiff or other tool of your choice
diff -u <($SCRIPT_DIR/pretty_json -f "$1") <($SCRIPT_DIR/pretty_json -f "$2")
#!/usr/bin/env node
// this script prettifies the json received as input. If you don't have node,
// write this in language of your choice or replace with sth like jq
// usage:
// pretty_json '{"json": 1}' '{"second": "json"}'
// pretty_json -f file1.json path/to/file2.json
const fs = require("fs");
const json = process.argv[2] !== '-f' ? process.argv[2] : fs.readFileSync(process.argv[3]);
console.log(JSON.stringify(JSON.parse(json), null, 2));
#!/usr/bin/env bash
SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
vimdiff <($SCRIPT_DIR/pretty_json -f "$1") <($SCRIPT_DIR/pretty_json -f "$2")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment