Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jq how to grab all values and use for script arguments

Tags:

json

jq

I have this vms.json

[
    {
        "name": "jms1",
        "port1": 24000,
        "port2": 25000,
        "port3": 26000
    },

    {
        "name": "jms2",
        "port1": 24001,
        "port2": 25000,
        "port3": 26001
    }
]

I have a port_script.sh which takes [name] [port1] [port2] [port3] as numbered arguments.

I can run this jq, to get keys, but I need to get values.

jq -r -c '.[] |keys' vms.json
["port1","name","port2","port3"]
["port1","name","port2","port3"]

I don't know how to use this output to get the associated values. If I can get the values I should be able to pipe them to my script via xargs.

Thanks in advance for your help

added: port_script.sh

#!/bin/bash
name=$1
port1=$2
port2=$3
port3=$4
vagrant ssh ${name} -- \
    -L ${port1}:127.0.0.1:${port1}  \
    -R ${port2}:127.0.0.1:${port2}  \
    -L ${port3}:127.0.0.1:${port3} 

Applying Santiago and Peak's responses - this works for me

eval "$(jq -r '.[] | ["./port_script.sh"] + [.name, .port1, .port2, .port3 | @sh] | join(" ")' vms.json)"
like image 552
mancocapac Avatar asked Sep 05 '25 03:09

mancocapac


1 Answers

Taking Santiago's answer one step further, you could write:

$ jq -r '.[] | "port_script.sh \"\(.name)\" \"\(.port1)\" \"\(.port2)\" \"\(.port3)\""'

With your input, this produces:

port_script.sh "jms1" "24000" "25000" "26000"
port_script.sh "jms2" "24001" "25000" "26001"

Or better yet perhaps:

$ jq -r --arg command port_script.sh '.[] 
  | $command + " \"\(.name)\" \"\(.port1)\" \"\(.port2)\" \"\(.port3)\""'

If the keys in each object are in the order required by the script, then we can generalize one step further so that the jq script will work for any number of keys:

jq -nr --arg command port_script.sh '
  .[] | $command + " " + ([.[]] | @sh)'

port_script.sh 'jms1' 24000 25000 26000
port_script.sh 'jms2' 24001 25000 26001

(Unfortunately, jq does not have a system subcommand, at least not yet.)

like image 198
peak Avatar answered Sep 07 '25 23:09

peak