Reputation: 85
I got below JSON example content.
{
"pools":[
{
"id":"403add1f-25d9-4a24-99ff-12c5559fecfa",
"loadbalancers":[
{
"id":"79970c9a-b0ba-4cde-a7e6-16b61641a7b8"
},
{
"id":"ranj-b0ba-4cde-a7e6-16b61641a7b8"
}
]
}
],
"pools_links":[
]
}
I would like to have content as below
403add1f-25d9-4a24-99ff-12c5559fecfa#79970c9a-b0ba-4cde-a7e6-16b61641a7b8,ranj-b0ba-4cde-a7e6-16b61641a7b8
I have tried to use below, however, I want to concatenate the id into 1 line instead of having 2 lines.
.pools[] | "\(.id),\(.loadbalancers[] | .id)"
Can anyone help me?
Upvotes: 0
Views: 199
Reputation: 7067
This should work:
jq -r '.pools[] | .id + "#" + ( [.loadbalancers[].id] | join(","))'
For each item in pools
it extracts the id
field, and joins all the loadbalancers[].id
fields.
Upvotes: 1
Reputation: 112
// say, this is your json
var json = "{\"pools\":[{\"id\":\"403add1f-25d9-4a24-99ff-12c5559fecfa\",\"loadbalancers\":[{\"id\":\"79970c9a-b0ba-4cde-a7e6-16b61641a7b8\"},{\"id\":\"ranj-b0ba-4cde-a7e6-16b61641a7b8\"}]}],\"pools_links\":[]}";
var obj = JSON.parse(json),
resultArr = [];
obj.pools.forEach(function(pool){
var id = pool.id,
balancers = [];
pool.loadbalancers.forEach(function(loadbalancer){
balancers.push(loadbalancer.id);
});
var result = id+'#'+balancers.join(',');
resultArr.push(result);
});
var joinResultsBy = '', // indicate any character to join the results by, if necessary
finalResult = resultArr.join(joinResultsBy);
console.log(finalResult);
Upvotes: 0