Home > Enterprise >  How to extract data from a JSON file into a variable
How to extract data from a JSON file into a variable

Time:11-22

I have the following json format, basically it is a huge file with several of such entries.

 [
      {
        "id": "kslhe6em",
        "version": "R7.8.0.00_BNK",
        "hostname": "abacus-ap-hf-test-001:8080",
        "status": "RUNNING",
           },
      {
        "id": "2bkaiupm",
        "version": "R7.8.0.00_BNK",
        "hostname": "abacus-ap-hotfix-001:8080",
        "status": "RUNNING",
      },
      {
        "id": "rz5savbi",
        "version": "R7.8.0.00_BNK",
        "hostname": "abacus-ap-hf-test-005:8080",
        "status": "RUNNING",
          },
          
    ]

I wanted to fetch all the hostname values that starts with "abacus-ap-hf-test" and without ":8080" into a variable and then wanted to use those values for further commands over a for loop something like below. But, am bit confused how can I extract such informaion.

HOSTAME="abacus-ap-hf-test-001 abacus-ap-hf-test-005"
for HOSTANAME in $HOSTNAME
do 
  sh ./trigger.sh
done

CodePudding user response:

The first line command update to this:

HOSTAME=$(grep -oP 'hostname": "\K(abacus-ap-hf-test[\w\d-] )' json.file)

or if you sure that the hostname end with :8080", try this:

HOSTAME=$(grep -oP '(?<="hostname": ")abacus-ap-hf-test[\w\d-] (?=:8080")' json.file)

you will find that abacus-ap-hf-test[\w\d-] is the regex, and other strings are the head or the end of the regex content which for finding result accuracy.

CodePudding user response:

Assuming you have valid JSON, you can get the hostname values using jq:

while read -r hname ; do  printf "%s\n" "$hname" ; done < <(jq -r .[].hostname j.json)

Output:

abacus-ap-hf-test-001:8080
abacus-ap-hotfix-001:8080
abacus-ap-hf-test-005:8080
  • Related