13

This question already has an answer here:

I am trying to curl some URL which returns a json file, then I want to parse hosts from it and create a comma separated string.

I have the first part working

curl -s -u "admin:admin" -H "X-Requested-By: ambari" "https://hbasecluster.net/api/v1/clusters/mycluster/services/ZOOKEEPER/components/ZOOKEEPER_SERVER" | jq -r '.host_components[].HostRoles.host_name'

which returns

zk0-mycluster.net
zk1-mycluster.net
zk2-mycluster.net

Now I want to join these into one string like

zk0-mycluster.net,zk1-mycluster.net,zk2-mycluster.net

marked as duplicate by don_crissti, GAD3R, Anthon, roaima, Eric Renouf Sep 28 '16 at 0:07

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

32

Do it in jq

jq -r '.host_components[].HostRoles.host_name | join(",")'

No, that's wrong. This is what you need:

jq -r '.host_components | map(.HostRoles.host_name) | join(",")'

Demo:

jq -r '.host_components | map(.HostRoles.host_name) | join(",")' <<DATA
{"host_components":[
  {"HostRoles":{"host_name":"one"}},
  {"HostRoles":{"host_name":"two"}},
  {"HostRoles":{"host_name":"three"}}
]}
DATA

outputs

one,two,three
  • +1, your answer should be the accepted one. I myself don't use jq too much. – cuonglm Sep 27 '16 at 17:28
  • 1
    just as an alternative, should also work: jq -r '[.host_components[].HostRoles.host_name] | join(",")' – webwurst Aug 13 at 15:40
  • @webwurst just tried, it's not working in case if you're selecting multiple columns/keys. For example: jq -r '[.host_components[].HostRoles.some_other_value, .host_components[].HostRoles.host_name] | join(",")]' – М.Б. Aug 14 at 16:41
9

paste is the best tool to do this job:

your_command | paste -sd, -
2

If you want to use awk, just print with no newline:

    <your command> | awk 'NR > 1 { printf(",") } {printf "%s",$0}'
  • You're very right. Thank you for your comment !!! Modified my command line. – Echoes_86 Sep 27 '16 at 14:15

Not the answer you're looking for? Browse other questions tagged or ask your own question.