jq 列印子物件中所有內容的鍵和值

jq 列印子物件中所有內容的鍵和值

我找到了這個問答使用列印物件中所有按鍵的解決方案:

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

就我而言,我想在子物件上執行上述操作:

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

執行此操作的正確語法是什麼?

答案1

只需通過管道即可keys運行:

樣本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

輸出:

host1, 10.1.2.3
host2, 10.1.2.2
host3, 10.1.18.1

答案2

一個更通用的 bash 函數來導出變數(帶有內插):

#
#------------------------------------------------------------------------------
# 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])"')
}

範例數據

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"
      }
  }
}

相關內容