Home > Net >  Return the value, if another value exists using jq
Return the value, if another value exists using jq

Time:11-17

I have a json fragment like below. I want to return the value of the name key together with the value of the version key if the version key has a value. It is better to have a solution with grep or jq

{
    {
      "slug": "polymer",
      "name": "Polymer",
      "description": null,
      "confidence": 100,
      "version": "3.5.0",
      "icon": "Polymer.png",
      "website": "http://polymer-project.org",
      "cpe": null,
      "categories": [
        {
          "id": 12,
          "slug": "javascript-frameworks",
          "name": "JavaScript frameworks"
        }
      ],
      "rootPath": true
    },
    {
      "slug": "google-ads",
      "name": "Google Ads",
      "description": "Google Ads is an online advertising platform developed by Google.",
      "confidence": 100,
      "version": null,
      "icon": "Google Ads.svg",
      "website": "https://ads.google.com",
      "cpe": null,
      "categories": [
        {
          "id": 36,
          "slug": "advertising",
          "name": "Advertising"
        }
      ]
    },
    {
      "slug": "hammer-js",
      "name": "Hammer.js",
      "description": null,
      "confidence": 100,
      "version": "2.0.2",
      "icon": "Hammer.js.png",
      "website": "https://hammerjs.github.io",
      "cpe": null,
      "categories": [
        {
          "id": 59,
          "slug": "javascript-libraries",
          "name": "JavaScript libraries"
        }
      ],

I expect this:

Polymer 3.5.0

Hammer.js 2.0.2

CodePudding user response:

With the alternative operator //, you can default to something else if the input happens to be falsy. With the empty function, you can simply discard that input.

jq -r '.[] | "\(.name) \(.version // empty)"'
Polymer 3.5.0
Hammer.js 2.0.2

Demo

CodePudding user response:

An alternate to @pmf's solution, making the same assumptions about the structure of the data: select the objects that have a "truthy" version:

jq -r '.[] | select(.version) | "\(.name) \(.version)"' file.json
  • Related