20

I found this Q/A with the solution to print all the keys in an object:

jq -r 'keys[] as $k | "\($k), \(.[$k] | .ip)"' 

In my case I want to perform the above but on a sub-object:

jq -r '.connections keys[] as $k | "\($k), \(.[$k] | .ip)"'

What is the proper syntax to do this?

Philip Kirkbride
  • 9,816
  • 25
  • 95
  • 167

2 Answers2

38

Simply pipe to keys function:

Sample input.json:

{
    "connections": {
        "host1": { "ip": "10.1.2.3" },
        "host2": { "ip": "10.1.2.2" },
        "host3": { "ip": "10.1.18.1" }
    }
}

jq -r '.connections | keys[] as $k | "\($k), \(.[$k] | .ip)"' input.json

The output:

host1, 10.1.2.3
host2, 10.1.2.2
host3, 10.1.18.1
RomanPerekhrest
  • 29,703
  • 3
  • 43
  • 67
  • 11
    `keys` sorts the keys, so it is worth pointing out that `keys_unsorted` does not. – peak Jan 07 '18 at 13:11
  • 2
    @peak, the OP wrote "*I found this https://stackoverflow.com/questions/34226370/jq-print-key-and-value-for-each-entry-in-an-object ...*" where the accepted answer clearly says "*`keys` produces the key names in sorted order; if you want them in the original order, use `keys_unsorted`*". So the OP is aware about that and have chosen `keys` consciously. – RomanPerekhrest Jan 07 '18 at 14:23
  • 7
    The comment was meant for others coming across this Q&A. – peak Jan 07 '18 at 15:06
1

A more generic bash function to export vars ( with interpolation ):

#
#------------------------------------------------------------------------------
# usage example:
# doExportJsonSectionVars cnf/env/dev.env.json '.env.virtual.docker.spark_base'
#------------------------------------------------------------------------------
doExportJsonSectionVars(){

   json_file="$1"
   shift 1;
   test -f "$json_file" || echo "the json_file: $json_file does not exist !!! Nothing to do" && exit 1

   section="$1"
   test -z "$section" && echo "the section in doExportJsonSectionVars is empty !!! nothing to do !!!" && exit 1
   shift 1;

   while read -r l ; do
      eval $l ;
   done < <(cat "$json_file"| jq -r "$section"'|keys_unsorted[] as $key|"export \($key)=\(.[$key])"')
}

example data

cat cnf/env/dev.env.json
{
  "env": {
    "ENV_TYPE": "dev",
      "physical": {
        "var_name": "var_value"
      },
      "virtual": {
          "docker": {
            "spark_base": {
                "SPARK_HOME": "/opt/spark"
              , "SPARK_CONF": "$SPARK_HOME/conf"
            }
            , "spark_master": {
              "var_name": "var_value"
            }
            , "spark_worker": {
              "var_name": "var_value"
            }
          }
          , "var_name": "var_value"
      }
  }
}
Yordan Georgiev
  • 269
  • 2
  • 4