jsonkeyjqintersect

Use jq to remove key/value pairs based on other file


I have 2 json files containing translations for my app:

en-US.json:

{
    "car": "car",
    "bike": "bike",
    "tree": "tree",
}

nl-NL.json:

{
    "car": "auto",
    "bike": "fiets",
    "tree": "boom",
    "house": "huis"
}

As you can see, I have removed the house from the en-US.json file (among many others). How could I remove the same house entry from my nl-NL.json file with jq? I basically want to get the intersection of both files, based on key.

I've been playing with jq 'keys' to get all keys, but that does not work. I think it should be found in the direction of jq --slurpfile en en-US.json 'del($en)' nl-NL.json but that totally does not work :( Any suggestions?


Solution

  • To reduce the nl-NL.json file to the keys present in en-US.json, you could read in the latter as reference, then select from the input turned into entries those keys that are present in the reference file. in checks "whether or not the input key is in the given object".

    jq --argfile ref en-US.json 'with_entries(select(.key | in($ref)))' nl-NL.json
    
    {
      "car": "auto",
      "bike": "fiets",
      "tree": "boom"
    }