Home > Back-end >  How to fetch values of json file using shell script?
How to fetch values of json file using shell script?

Time:12-07

I have a sample json file shown below:

 {
  "component": {
    "id": "xxxxxxxx",
    "key": "abc",
    "name": "project",
    "qualifier": "TRK",
    "measures": [
      {
        "metric": "ncloc",
        "value": "43"
      },
      {
        "metric": "bugs",
        "value": "0",
        "bestValue": true
      },
      {
        "metric": "blocker_violations",
        "value": "0",
        "bestValue": true
      },
      {
        "metric": "info_violations",
        "value": "0",
        "bestValue": true
      },
      {
        "metric": "critical_violations",
        "value": "0",
        "bestValue": true
      },
      {
        "metric": "vulnerabilities",
        "value": "0",
        "bestValue": true
      },
      {
        "metric": "major_violations",
        "value": "0",
        "bestValue": true
      },
      {
        "metric": "code_smells",
        "value": "0",
        "bestValue": true
      },
      {
        "metric": "minor_violations",
        "value": "0",
        "bestValue": true
      },
      {
        "metric": "reliability_rating",
        "value": "1.0",
        "bestValue": true
      },
      {
        "metric": "security_rating",
        "value": "1.0",
        "bestValue": true
      }
    ]
  }
}

From the above .json file I need to fetch metric and its respective value as : say 'bugs:0'. I do find related blogs but bit confused.

my usecase: I want to read all metric values and if any of value is <> 0 then exit 1 is to be executed else exit 0. I tried below one just for one metric.

if [  jq -r '.component.measures[].info_violations.value'!= 0 ]
then 
exit 1
else
exit 0

The code isn't throwing any error, but I am sure that it is incorrect logic and just tried for single metric. Now I am clear with my use-case, I hope someone can help me.

I need to fetch all metrics and corresponding values for items in measures[]

CodePudding user response:

YOu can use the following JQ filter to check if any of the values equals 0:

.component.measures | any(.value == "0")

Thanks to @Glenn for pointing out --exit-status, this lets JQ exit with the status you'll need. So we can use that as exit value, using $?:

#!/bin/bash

jq --exit-status '.component.measures | any(.value == "0")' input
exit $?

JqPlay
  • Related