JQ根据变量值获取key

JQ get key based on variable value

我正在尝试根据 Wade Wegner 的指南 here. In order to get the value I want I need to expand how he is using JQ 为 Salesforce 的 DX CLI 创建一个 ohmyzsh 函数,我以前从未听说过。我得到了这个用例的前提,但我正在努力处理一个抽象点(在 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": "myemail@domain.com",        
        "my-scrath-org": "test-jdj1iflkor4k@mydomain.net"
    }
}

使用 ${defaultusername} 我知道这种情况下的值是 "test-jdj1iflkor4k@mydomain.net",因此我需要它将 defaultusernamealias 的值设置为 "my-scrath-org"

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

我想我在这里弄明白了:

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

这让我可以像这样显示我当前的默认用户名组织:

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

恭喜您了解如何使用 to_entries

一个小建议是避免对 "construct" jq 程序使用 shell 插值。实现预期目标的更好方法是在命令行中传递相关值。在您的情况下,以下内容是合适的:

$ 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'