skip to Main Content

From the json change_tasks array below I would like to extract only the values of the key "description" when the key:value is an exact match of "short_description": "01. Project validation".

{
    "change_tasks": [{
        "active": "true",
        "approval": "Not Yet Requested", 
        "description": "testing",
        "short_description": "Test description",
        "state": "-5",
        "state_description": "Pending",
        "sys_class_name": "Change Task",
        "sys_created_on": "2023-05-10 15:23:50",
        "sys_updated_on": "2023-05-10 15:25:58",
        "time_worked": "",
        "u_actions_taken_to_prevent_recurrence": "",
        "u_createdby_businessappid": ""
    }, 
    {
        "active": "true",
        "approval": "Not Yet Requested",
        "description": "value-01, value-02",
        "short_description": "01. Project validation",
        "state": "-5",
        "state_description": "Pending",
        "sys_class_name": "Change Task",
        "sys_created_on": "2023-05-10 15:21:01",
        "sys_updated_on": "2023-05-10 15:25:58",
        "time_worked": "",
        "u_actions_taken_to_prevent_recurrence": "",
        "u_createdby_businessappid": ""
    }],
    "responseSummary": {
        "message": "Search successfully executed",
        "code": "200",
        "businessUnit": "unit1",
        "businessAppId": "123456",
        "numRecordsReturned": "2",
        "totalRecords": "2",
        "hasMore": "false"
    }
}

This query gives me the output of the correct change task but I only require the values of "description" when "short_description" is "01. Project validation". Also the change tasks value I want will not always be [1] it could be any in the list of objects.

$ jq -r .change_tasks[1].short_description test.json
01. Project validation

I will then need to turn the comma separated values of "description" into variables so they can be checked against another list of values in bash.

2

Answers


  1. Chosen as BEST ANSWER

    I ended up sorting it myself like this in the end

    #!/bin/sh
    
    variable=$(jq -r '.change_tasks[] | select(.short_description=="01. Project validation").description' test.json)
    
    for i in ${variable//,/ }
    do
        # call your procedure/other scripts here below
        echo "$i"
    done
    

  2. You can use:

    $ jq -r '.change_tasks[] | select(.short_description == "01. Project validation").description | gsub(",\s+";",") | split(",") | @sh ' test.json
    'value-01' 'value-02'
    

    if you want to read this into two variables:

    function get_values {
        jq -r '.change_tasks[] | select(.short_description == "01. Project validation").description | gsub(",\s+";",") | split(",") | @sh ' test.json
    }
    
    read value1 value2<<<$(get_values)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search