【问题标题】:How to extract an attribute's value from JSON object when another attribute's value from same object is known当来自同一对象的另一个属性值已知时,如何从 JSON 对象中提取一个属性值
【发布时间】:2022-08-17 17:54:16
【问题描述】:

在 bash shell 脚本中,我想从以下 JSON 中提取 Arn、DefaultVersionId,其中 Arn 字符串包含单词阿克谢:

[
    {
            \"PolicyName\": \"my-buckets-all\",
            \"PolicyId\": \"ABCDEF\",
            \"Arn\": \"arn:aws:iam::12345:policy/my-buckets-all\",
            \"Path\": \"/\",
            \"DefaultVersionId\": \"v1\",
            \"AttachmentCount\": 0,
            \"PermissionsBoundaryUsageCount\": 0,
            \"IsAttachable\": true,
            \"CreateDate\": \"2022-05-14T01:17:13+00:00\",
            \"UpdateDate\": \"2022-05-14T01:17:13+00:00\"
        },
        {
            \"PolicyName\": \"akshay-buckets-all\",
            \"PolicyId\": \"GHIJK\",
            \"Arn\": \"arn:aws:iam::12345:policy/akshay-buckets-all\",
            \"Path\": \"/\",
            \"DefaultVersionId\": \"v4\",
            \"AttachmentCount\": 1,
            \"PermissionsBoundaryUsageCount\": 0,
            \"IsAttachable\": true,
            \"CreateDate\": \"2022-05-20T21:20:10+00:00\",
            \"UpdateDate\": \"2022-07-28T19:15:09+00:00\"
        }
]

我正在摆弄jq 来完成这项工作。尝试以下操作时,我只得到Arn 而不是DefaultVersionId:

.[] | .Arn, .DefaultVersionId | select(contains(\"akshay\"))

怎么办?

jqplay 在这里提琴:https://jqplay.org/s/gp1DYAG-rgU

    标签: json bash amazon-web-services shell jq


    【解决方案1】:

    您需要先过滤所需的对象(根据您的条件),然后提取所需的字段,即

    map( select( .Arn | contains( "akshay" ) )? )[] | .Arn, .DefaultVersionId
    

    获取多行输出的值。

    【讨论】:

      猜你喜欢
      • 2021-09-10
      • 2019-09-11
      • 1970-01-01
      • 1970-01-01
      • 2022-11-10
      • 1970-01-01
      • 2017-06-07
      • 2011-04-03
      • 2012-04-03
      相关资源
      最近更新 更多