Reputation: 673
Is there a way to combine multiple values for a specific key separated by comma. In my case i am trying to print multiple service.names
values so they can be printed in a single line separated by comma.
How can i combine the service.name
values separated by comma so they print like below:
{
"number": 1,
"service name": "FTP-Server, SSH-Server"
}
I tried below in pyjq but it separates values by a complete separate block.
.group[].group[] | { "number": .number, "service name": .service[].name }
Here is the output i am getting
{
"number": 1,
"service name": "FTP-Server"
}
{
"number": 1,
"service name": "SSH-Server"
}
Given below same data with/without object-dictionary. I am ok with any format.
JSON file with object-dictionary enabled
{
"objects-dictionary": [
{
"name": "FTP-Server",
"port": "21",
"type": "service-tcp",
"uid": "ef245528-9a3d-11d6-9eaa-3e5a6fdd6a6a"
},
{
"name": "SSH-Server",
"port": "22",
"type": "service-tcp",
"uid": "dff4f7ba-9a3d-11d6-91c1-3e5a6fdd5151"
}
],
"base": [
{
"number": 1,
"service": [
"ef245528-9a3d-11d6-9eaa-3e5a6fdd6a6a",
"dff4f7ba-9a3d-11d6-91c1-3e5a6fdd5151"
],
"uid": "90088436-ac42-4363-84a6-3dbebf3c11f0"
}
]
}
JSON file without object-dictionary
{
"group": [
{
"group": [
{
"number": 1,
"service": [
{
"name": "FTP-Server",
"port": "21",
"type": "service-tcp",
"uid": "ef245528-9a3d-11d6-9eaa-3e5a6fdd6a6a"
},
{
"name": "SSH-Server",
"port": "22",
"type": "service-tcp",
"uid": "dff4f7ba-9a3d-11d6-91c1-3e5a6fdd5151"
}
],
"uid": "90088436-ac42-4363-84a6-3dbebf3c11f0"
}
]
}
]
}
Upvotes: 0
Views: 760
Reputation: 116957
With your second JSON text, the following filter:
.group[].group[]
| { "number": .number, "service name": ([.service[].name]|join(", ")) }
produces the output that you've indicated you expected (including the space after the comma):
{
"number": 1,
"service name": "FTP-Server, SSH-Server"
}
Upvotes: 0
Reputation: 13259
It's rather unclear what you expect as output, but given your last example and using jq
you can concatenate both service names together:
<file jq '[.group[].group[].service[].name] | join(",")'
Note that join
expects an array, so the name
s need to be inside an array [ ... ]
.
If you need to add this string within the object itself, you might do something like:
<file jq '.service.name=([.group[].group[].service[].name] | join(","))'
Upvotes: 1