From,
jq '.DistributionList.Items[] | select(.Aliases.Items != null) | .Id "," .DomainName' << EOF
{
"DistributionList": {
"Items": [
{
"Id": "EG3MOA",
"Status": "Deployed",
"LastModifiedTime": "2022-12-03T19:32:35.007000 00:00",
"DomainName": "a***.cloudfront.net",
"Aliases": {
"Quantity": 1,
"Items": [
"a.domain.tld",
"b.domain.tld"
]
}
},
{
"Id": "EG3MOB",
"Status": "Deployed",
"LastModifiedTime": "2022-12-03T19:32:35.007000 00:00",
"DomainName": "b***.cloudfront.net",
"Aliases": {
"Quantity": 1,
"Items": [
"c.domain.tld",
"d.domain.tld"
]
}
}
]
}
}
EOF
It yields:
"EG3MOA,a***.cloudfront.net"
"EG3MOB,b***.cloudfront.net"
How would I also get the `Alias Items, so that I have:
"EG3MOA,a***.cloudfront.net,'a.domain.tld,b.domain.tld'"
"EG3MOB,b***.cloudfront.net,'c.domain.tld,d.domain.tld'"
CodePudding user response:
To extract the Aliases.Items array and combine it into a single string, you can use the join() method in jq. For example, this jq filter would extract the Id, DomainName, and Aliases.Items values and combine them into a single string, with the Aliases.Items values joined together with a comma:
jq '.DistributionList.Items[] | select(.Aliases.Items != null) | .Id "," .DomainName ",'" (.Aliases.Items | join(",")) "'"
Here's an example of how you could use this filter in your command:
jq '.DistributionList.Items[] | select(.Aliases.Items != null) | .Id "," .DomainName ",'" (.Aliases.Items | join(",")) "'" << EOF
{
"DistributionList": {
"Items": [
{
"Id": "EG3MOA",
"Status": "Deployed",
"LastModifiedTime": "2022-12-03T19:32:35.007000 00:00",
"DomainName": "a***.cloudfront.net",
"Aliases": {
"Quantity": 1,
"Items": [
"a.domain.tld",
"b.domain.tld"
]
}
},
{
"Id": "EG3MOB",
"Status": "Deployed",
"LastModifiedTime": "2022-12-03T19:32:35.007000 00:00",
"DomainName": "b***.cloudfront.net",
"Aliases": {
"Quantity": 1,
"Items": [
"c.domain.tld",
"d.domain.tld"
]
}
}
]
}
}
EOF
This should output the following:
"EG3MOA,a***.cloudfront.net,'a.domain.tld,b.domain.tld'"
"EG3MOB,b***.cloudfront.net,'c.domain.tld,d.domain.tld'"
CodePudding user response:
If you are struggling to enclose an apostrophe '
with JSON string quotes "
withing a jq filter enclosed again by apostrophes, you can use the codepoint notation instead: \u0027
jq '… | "\(.Id),\(.DomainName),\u0027\(.Aliases.Items | join(","))\u0027"'