How to use Shell tool jsondiff.sh
Today, I will talk to you about how to use the Shell tool jsondiff.sh, which may not be well understood by many people. In order to make you understand better, the editor has summarized the following contents for you. I hope you can get something according to this article.
Recently, I was busy refactoring a history project, but due to objective conditions, there were no test cases available, so I had to judge right or wrong by comparing the result sets of new and old servers. Since laziness is a programmer's virtue, I think I'd better write a tool, plus the result set is JSON, so I have jsondiff.sh.
The logic is very simple, nothing more than to get the result sets on different servers through curl, and then diff, but there are a few points to note here: first, JSON on one line, direct diff will lose its meaning; second, Chinese characters in JSON will be encoded, which is not easy to view; in addition, the order of fields in JSON does not matter, so it is sorted before diff. To be clear, instead of using Bash when formatting JSON data, I used PHP:
#! / bin/bash RM=/bin/rm PHP=/usr/bin/php CURL=/usr/bin/curl DIFF=/usr/bin/diff VIMDIFF=/usr/bin/vimdiff COLORDIFF=/usr/bin/colordiff usage () {echo "Usage: $0-- uri=-- old=-- new="} format () {$PHP-R 'function ksort_recursive (& $array) {if (! is_array ($array)) {return } ksort ($array); foreach (array_keys ($array) as $key) {ksort_recursive ($array [$key]);}} $options = JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE; $array = json_decode ($argn, true); ksort_recursive ($array); echo json_encode ($array, $options) '} request () {$CURL-s-H "Host: $1"http://$2$3"} eval set-- $(getopt-Q-o" h "- l" host:,uri:,old:,new:,vim,help "- -" $@ ") while true; do case" $1 "in-- host) HOST=$2; shift 2;-- uri) URI=$2; shift 2 -- old) OLD=$2; shift 2;-- new) NEW=$2; shift 2;-- vim) VIM= "Y"; shift 1;-h |-- help) usage; exit 0; -) break;; esac done if [[- z "$URI" |-z "$OLD" | |-z "$NEW"]] Then usage exit 1 fi if [[- z "$HOST"]; then HOST= "www.foobar.com" fi OLD_FILE=$ (mktemp) NEW_FILE=$ (mktemp) request "$HOST"$OLD"$URI" | format > $OLD_FILE request "$HOST"$NEW"$URI" | format > $NEW_FILE if [["$VIM" = "Y"]]; then $VIMDIFF $OLD_FILE $NEW_FILE elif [[- x "$COLORDIFF"]] Then $COLORDIFF-u $OLD_FILE $NEW_FILE else $DIFF-u $OLD_FILE $NEW_FILE fi $RM-f $OLD_FILE $RM-f $NEW_FILE
The usage of "getopt" is worth noting. The relevant references are as follows:
Getopt in Bash Bash: Preserving Whitespace Using set and eval
Although my Shell level is limited, I try to make it as easy to use as possible: multiple tools are allowed in diff, "colordiff" is preferred by default, and "vimdiff" can be activated if necessary.
After reading the above, do you have any further understanding of how to use the Shell tool jsondiff.sh? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.