I have a file that looks as below:
{
"Job": {
"Name": "sample_job",
"Role": "sample_role_job"
},
"DefaultArguments": {
"--enable-continuous-cloudwatch-log": "",
"--enable-metrics": ""
},
"Timeout": 2880,
"NumberOfWorkers": 10
}
}
I want to get key/value from "Name"
, "--enable-continuous-cloudwatch-log": ""
and "--enable-metrics": ""
. So, I need to show the info like this:
"Name" "sample_job"
"--enable-continuous-cloudwatch-log" ""
"--enable-metrics" ""
CodePudding user response:
Since you're JSON isn't valid, I've converted it into:
{
"Job": {
"Name": "sample_job",
"Role": "sample_role_job"
},
"DefaultArguments": {
"--enable-continuous-cloudwatch-log": "test_1",
"--enable-metrics": ""
},
"Timeout": 2880,
"NumberOfWorkers": 10
}
Using the following filter:
"Name \(.Job.Name)\n--enable-continuous-cloudwatch-log \(.DefaultArguments."--enable-continuous-cloudwatch-log")\n--enable-metrics \(.DefaultArguments."--enable-metrics")"
We use string interpolation to show the desired output:
Name sample_job
--enable-continuous-cloudwatch-log test_1
--enable-metrics
jq --raw-output '"Name \(.Job.Name)\n--enable-continuous-cloudwatch-log \(.DefaultArguments."--enable-continuous-cloudwatch-log")\n--enable-metrics \(.DefaultArguments."--enable-metrics")"'
Online Demo
CodePudding user response:
Do this in a two-step process. Extract the desired key-value pairs, as an object and apply the required string transformation. In jq
this is done as
(.Job | { Name })
(.DefaultArguments | { "--enable-continuous-cloudwatch-log", "--enable-metrics"}) |
to_entries[] | "\"\(.key)\" \"\(.value)\""
Or you can trim out specifying the objects explicitly under DefaultArguments
, if those two are the only objects present i.e.
(.Job | { Name }) (.DefaultArguments) |
to_entries[] | "\"\(.key)\" \"\(.value)\""
or if there are more objects present, select them instead of mentioning the names explicitly i.e. as
(.Job | { Name })
(.DefaultArguments | with_entries(select(.key | startswith("--enable"))))) |
to_entries[] | "\"\(.key)\" \"\(.value)\""
Use the above filter(s) in --raw-output
mode. See jqplay