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.
2
Answers
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 thetostream
filter, and thendiff
their results (usingjq -c
further reduces the amount of output to diff):Here’s an efficient solution for the case where there is exactly one top-level object. It’s efficient for several reasons, including that it’s a jq-only solution (e.g., no need for
diff
), and that jq is only called once.Output for the sample input: