Reputation: 119
I have a very long JSON file with the following structure (there are no nested attributes):
{
"Aaa aaa aaa": "Aaa aaa aaa",
"Bbb bbb bbb": "Bbb bbb bbb",
"Ccc ccc ccc": "Xxx xxx xxx",
"Ddd ddd ddd": "Ddd ddd ddd",
"Eee eee eee": "Yyy yyy yyy"
}
And I need to print those pairs whose key does not match the value. In this example, I'm expecting this kind of result:
"Ccc ccc ccc": "Xxx xxx xxx",
"Eee eee eee": "Yyy yyy yyy"
I know how to capture and print keys and values with sed...
sed -n "s/^\t\"\(.*\)\": \"\(.*\)\",\?$/\1 \2/p" file.json
...but I do not know how to make the comparison between both groups. Maybe sed is not the right tool for this task and I should be using awk or jq instead, however in don't have any experience with the latter.
Therefore, which would be the right way or tool to search differences in name-value pairs within a JSON file?
Upvotes: 0
Views: 82
Reputation: 85530
In jq
you can use the with_entries()
function. It puts the keys and values of each record in the object into named variables .key
and .value
and you basically have to evaluate if they are not the same.
jq 'with_entries(select(.key != .value))'
See with_entries(..) from the manual to know more
Follow-up question to do a case insensitive comparison. Can be done by converting both key/value to a particular case
with_entries(select( (.key| ascii_downcase) != (.value| ascii_downcase)))
Upvotes: 1
Reputation: 99084
sed '/\(\".*\"\): \1/d' file.json
Or if you also want to eliminate the braces:
sed '/\"/!d;/\(\".*\"\): \1/d' file.json
Upvotes: 1