1
{
   "name": "ford",
   "availableVersions": [
      {
         "version": 111,
         "count": 3
      },
      {
         "version": 122,
         "count": 2
      },
      {
         "version": 133,
         "count": 3
      }
                          ],
       "RealVersion": 133


}
{
   "name": "bmw",
   "availableVersions": [
     {
         "version": 144,
         "count": 1
     },
     {
      "version": 155,
      "count": 3
     }                  ],
     "RealVersion": 120

    }

I have this demo.json file now if (count == 3) I want to concatenate the name with the version.

So my output should be [ford:111,ford:133,BMW:155]. I am using json parsing with jq.

I was using this command which worked fine

cat demo2| jq '.name + ": " + (.availableVersions[]|select(.count == 3).version|tostring)'

But now i also want one more conditon if (count ==3 and version != RealVersion) then only i want the version I tried a lot of command none of them are working. Can someone help me with this?

So EXPECTED OUTPUT = [ford:111,BMW:155] So, ford:133 would not come in the output

  • Does this answer your question? [Concat 2 fields in JSON using jq](https://stackoverflow.com/questions/37710718/concat-2-fields-in-json-using-jq) – David C. Apr 05 '20 at 05:20

2 Answers2

1

Here is a way which captures .RealVersion with an as earlier in the filter then uses it in the select.

.name + ": " + (
    .RealVersion as $r
  | .availableVersions[]
  | select(.count == 3 and .version != $r).version 
  | tostring
)

Sample output

"ford: 111"
"bmw: 155"

Try it online!

jq170727
  • 13,159
  • 3
  • 46
  • 56
0

Converting multiple input "blobs" to a single output blob requires -s|--slurp, which is not very memory-efficient. Please be sure this is a requirement before you implement it.

jq --compact --slurp '
    .[] |= . as $r
        | .availableVersions[]
        | select(.count == 3 and .version != $r.RealVersion)
        | "\($r.name):\(.version)"
'

Output:

["ford:111","bmw:155"]
vintnes
  • 2,014
  • 7
  • 16