Search code examples
zshaws-cli

How to extract individual values from output aws cli --query


I'm running this query with zsh:

output=$(aws sagemaker describe-training-job \
    --training-job-name $name \
    --query '{S3ModelArtifacts:ModelArtifacts.S3ModelArtifacts,TrainingImage:AlgorithmSpecification.TrainingImage,RoleArn:RoleArn}')

But for the life of me I can't seem to individually extract out S3ModelArtifacts, TrainingImage, and RoleArn.

It seems to be neither an array nor an associative array? But it looks like it's json format when I do echo $output.

Ultimately I just want to be able to do something like var=${output[TrainingImage]} but this just gives me the whole response instead of just the TrainingImage value.

Any help appreciated.


Solution

  • You can use the command line tool jq to parse json output like so:

    (19-11-27 10:25:38) <0> [~] printf %s "$output" | jq '.TrainingImage'
    "123456789877.dkr.ecr.eu-west-1.amazonaws.com/kmeans:1"
    

    Or, as this is a pretty simple query, you can use sed:

    (19-11-27 10:25:43) <0> [~] printf %s "$output" | sed -n -e 's/^.*TrainingImage"://p'
     "123456789877.dkr.ecr.eu-west-1.amazonaws.com/kmeans:1",
    

    Here is the explanation of the sed command.