0

JQ : Sort a JSON file using another JSON as "order" model

I'm trying to compare two JSON file, but because a lot of "reordering" happened, i wish to "sort" the second file using the first one as a "model", basically moving all the fields to match the position in the first one.

I'm using winmerge which use a plugin that's actually just JQ, so i can't pass only one file and i need to pass the two together

is there an argument for this I know there is "-S" but that sort both files

Here are two of the files i'm using, there are a lil big also don't worry about it's content

https://pastebin.com/Z8p1nVDs Left side

https://pastebin.com/X3Jq42S0 Right side

Oshida_BCF
  • 11
  • 3

1 Answers1

0

Assuming we have only to deal with top-level keys, the following approach would suffice.

input.json:

{"b":1, "a":2, "x": 3}

reference.json

{"a":10, "b":20, "y": 30}
< input.json | jq --argfile reference reference.json '
  . as $in
  | ($reference|keys_unsorted) as $refkeys
  | (keys_unsorted - $refkeys) as $remainder
  | reduce ($refkeys[], $remainder[]) as $k ({};
      if $in|has($k) then .[$k] = $in[$k] else . end)
'

There are of course many ways to provide the two JSON files.

peak
  • 105,803
  • 17
  • 152
  • 177