Comparing two json files : shell scripting

2020-05-24 06:24发布

问题:

I would like to compare two json files which look like the following:

[
   {
      "type" : 1,
      "children" : {
         "nsubj" : {
            "role" : "topic",
            "POS" : [
               "noun"
            ]
         }
      },
      "role" : "vehicle",
      "POS" : [
         "noun"
      ]
   },

and the other is in the similar format, but there are some differences between the two because one json file is made up of 3336 lines, while another is made up of 3724 lines. I would like to write a shell script which would compare the two line by line and whenever it finds a difference, output the line number where the difference occurred.

回答1:

Just use diff. Like in

diff --unified file1.json file2.json


回答2:

To compare json files you should convert them so they have same order of keys. Very good tool for this job is jq (https://stedolan.github.io/jq/) where you can do:

jq -S . fileA.json > fileA_fmt.json
jq -S . fileB.json > fileB_fmt.json

then, you can use your favourite tool for text file comparison. I like kdiff3 for GUI or just plain diff when in pure command-line e.g.:

diff fileA_fmt.json fileB_fmt.json


标签: json shell