JQ根据变量值获取密钥

问题描述 投票:0回答:2

我正在尝试基于Wade Wegner的指南here为Salesforce的DX CLI创建一个ohmyzsh函数。为了得到我想要的价值,我需要扩展他如何使用我之前从未听说过的JQ。我得到了这个用例的前提,但我正在努力解决一个抽象点(在aliasConfig json中)。到目前为止,这是我的脚本

get_sfdx_defaultusername() {
    config="$(cat .sfdx/sfdx-config.json 2> /dev/null)";
    globalConfig="$(cat ~/.sfdx/sfdx-config.json)";
    aliasConfig="$(cat ~/.sfdx/alias.json)";

    defaultusername="$(echo ${config} | jq -r .defaultusername)"
    defaultusernamealias="NEED HELP HERE"
    globaldefaultusername="$(echo ${globalConfig} | jq -r .defaultusername)"

    if [ ! $defaultusernamealias = "null" ]
    then
      echoString=$echoString$defaultusernamealias"$txtylw (alias)"
    elif [ ! $defaultusername = "null" ]
    then
      echoString=$echoString$defaultusername"$txtylw (local)"
    else
      echoString=$echoString$globaldefaultusername"$txtylw (global)"
    fi
    echo $echoString"\n"
}

alias.json看起来像这样:

{
    "orgs": {
        "HubOrg": "[email protected]",        
        "my-scrath-org": "[email protected]"
    }
}

使用${defaultusername}我知道这个案例的值是“[email protected]”,因此我需要它将defaultusernamealias的值设置为“my-scrath-org”

注意:我找到的最接近的答案是this,但不幸的是我仍然无法得到我需要的东西。

bash sh jq oh-my-zsh
2个回答
2
投票

恭喜你弄清楚如何使用to_entries

一个小建议是避免使用shell插值来“构造”jq程序。实现预期目标的更好方法是在命令行上传递相关值。在您的情况下,以下是适当的:

$ jq --arg username "$defaultusername" '
  .orgs | to_entries[] | select(.value == $username ).key'

另一个小问题是避免使用echo将JSON发送到STDIN。有几种可能性,包括这些模式:

  • 如果你使用bash:jq .... <<< "$JSON"
  • 使用printf "%s" "$JSON" | jq ...
  • jq -n --argjson JSON "$JSON" '$JSON | ...'

在您的情况下,这些替代方案中的最后一个将如下所示:

$ jq --arg username "$defaultusername" --argjson JSON "$aliasConfig" '
    $JSON
    | .orgs | to_entries[] | select(.value == $username ).key'

0
投票

我想我在这里弄清楚了:

get_sfdx_defaultusername() {
    config="$(cat .sfdx/sfdx-config.json 2> /dev/null)";
    globalConfig="$(cat ~/.sfdx/sfdx-config.json)";
    aliasConfig="$(cat ~/.sfdx/alias.json)";

    defaultusername="$(echo ${config} | jq -r .defaultusername)"
    defaultusernamealias="$(echo ${aliasConfig} | jq -r '.orgs | to_entries[] | select(.value =="'$defaultusername'").key' )"
    globaldefaultusername="$(echo ${globalConfig} | jq -r .defaultusername)"

    if [ ! $defaultusernamealias = "null" ]
    then
        echoString=$echoString$defaultusernamealias"$txtylw (alias)"
    elif [ ! $defaultusername = "null" ]
    then
        echoString=$echoString$defaultusername"$txtylw (local)"
    else
        echoString=$echoString$globaldefaultusername"$txtylw (global)"
    fi
    echo $echoString"\n"
}

这允许我像这样显示我当前的defaultusername org:enter image description here

如果有人有兴趣使用它或贡献它,我发布了github repo here

© www.soinside.com 2019 - 2024. All rights reserved.