Comparing two json files : shell scripting

2020-05-24 06:36发布

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.

标签: json shell
2条回答
Viruses.
2楼-- · 2020-05-24 06:54

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
查看更多
爱情/是我丢掉的垃圾
3楼-- · 2020-05-24 07:12

Just use diff. Like in

diff --unified file1.json file2.json
查看更多
登录 后发表回答