I would like to print each path and value of a json file with included key values line by line. Given the following json and jq, is it also possible to add the values for each line? If not using jq is there another way? I am thinking of something vaguely similar to snmpwalk for json. Also, is there a technical term for what I am trying to do?
$ cat short.json | jq '.'
{
"Reservations": [
{
"Groups": [],
"Instances": [
{
"ImageId": "ami-a",
"InstanceId": "i-a",
"InstanceType": "t2.micro",
"KeyName": "ubuntu"
}
]
}
]
}
$ cat short.json | jq -r '[paths | map(.|tostring) | join(".")]'
[
"Reservations",
"Reservations.0",
"Reservations.0.Groups",
"Reservations.0.Instances",
"Reservations.0.Instances.0",
"Reservations.0.Instances.0.ImageId",
"Reservations.0.Instances.0.InstanceId",
"Reservations.0.Instances.0.InstanceType",
"Reservations.0.Instances.0.KeyName"
]
Example of a single line from the multiline output:
"Reservations.0.Instances.0.ImageId": "ami-a",
Bonus if the output could be formatted to be used in jq using copy and paste with value easily detached using linux cut:
'.Reservations[].Instances[].ImageId': "ami-a"
$ cat short.json | jq -r '.Reservations[].Instances[].ImageId'
ami-a
Best Answer
I'm not super knowledgeable on
jq
but I found this on the interwebs and I think it will work in your case:Cut and paste version:
Easy(er) to read version:
Result:
And because I want the bonus points, here's a hacky
sed
you can tack on to get the output you want:Which outputs: