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?

0

2 Answers 2

37

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
3
  • 11
    keys sorts the keys, so it is worth pointing out that keys_unsorted does not.
    – peak
    Jan 7, 2018 at 13:11
  • 2
    @peak, the OP wrote "I found this stackoverflow.com/questions/34226370/… ..." 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. Jan 7, 2018 at 14:23
  • 7
    The comment was meant for others coming across this Q&A.
    – peak
    Jan 7, 2018 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"
      }
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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