Home > Mobile >  Select objects from file A where value of path appear in file B in jq
Select objects from file A where value of path appear in file B in jq

Time:02-02

I want to filter with jq the objects from json content of this fileA

[
  {
    "id": "bird",
    "content": {
        "key1": "a"
    }
  },
  {
    "id": "dog",
    "content": {
        "key1": "b"
    }
  },
  {
    "id": "cat",
    "content": {
        "key1": "c"
    }
  }
]

Where the id appear in this json content of fileB called theId (the sort order has no importance) :

[
  {
    "theId": "cat"
  },
  {
    "theId": "bird"
  }
]

Expected result (the sort order has no importance) :

[
  {
    "id": "cat",
    "content": {
        "key1": "c"
    },
    "id": "bird",
    "content": {
        "key1": "a"
    }
  }
]

I think I can do this in a bash loop :

  1. looping on ids from fileB
  2. execute jq to extract the given id such as
jq -c "map(select(.id | contains(\"$id\")))"

but I have to separate them with , which seems dirty.

I don't know how to say to jq the filter is composed of values of the given array which is stored in fileB

Is it possible ?

CodePudding user response:

Here is one way:

$ jq 'map(.theId) as $ids | input | map(select(.id | IN($ids[])))' fileB fileA
[
  {
    "id": "bird",
    "content": {
      "key1": "a"
    }
  },
  {
    "id": "cat",
    "content": {
      "key1": "c"
    }
  }
]

CodePudding user response:

A simple solution using --slurpfile:

jq --slurpfile b fileB 'map(select(.id|IN($b[][].theId)))' fileA
  • Related