Search code examples
jsonduplicateskeyjq

Report duplicate object keys


How do you use jq to detect and report duplicate object keys? For example, the following JSON has duplicate key on .a.

{
  "a":{
    "b": 1
  },
  "a":{
    "c": 1
  }
}

I think using --stream is required but I can't quite get it right.

Edit: cannot assume the dup can exist only as the top level key. The dup may exist at any level.


Solution

  • If you don't mind running jq twice, you could produce the stream once "externally" (before collapsing duplicates) with the --stream flag, and once "internally" (after collapsing duplicates) with the tostream filter, and then diff their results (using jq -c further reduces the amount of output to diff):

    diff -qs <(jq -c --stream . file.json) <(jq -c tostream file.json)