简体   繁体   English

用jq从json中的一行中提取值 Linux bash

[英]Extract values from an array in json in one line in Linux bash with jq

I am extending here my recent question about jq since my requirements changed and I am still confused with map function.我在这里扩展我最近关于 jq 的问题,因为我的要求发生了变化,我仍然对 map function 感到困惑。

Given such a service-def-test.json (very simplified from my real use case):给定这样一个 service-def-test.json(从我的实际用例中非常简化):

{
    "definition": {
        "services": [{
                "image": {
                    "name": "img1",
                    "tag": "2.0.1"
                }
            }, {
                "image": {
                    "name": "img2",
                    "tag": "1.4.0"
                }
            }, {
                "image": {
                    "name": "img3",
                    "tag": "1.2.5"
                }
            }
        ]
    }
}

I now would like to get a one-line list of values:我现在想得到一个值的单行列表:

[img1:2.0.1, img2:1.4.0, img3:1.2. [img1:2.0.1, img2:1.4.0, img3:1.2。
to store eventually in a COMPONENT_IMAGES variable.最终存储在 COMPONENT_IMAGES 变量中。

From the previous answer,从之前的回答来看,

jq -r '.definition.services | " "COMPONENT_IMAGES=\"\(map(.image.name, .image.tag) | join(", "))\"" ' service-def-test.json

generates产生

COMPONENT_IMAGES="img1, 2.0.1, img2, 1.4.0, img3, 1.2.5"

but this I want only 3 items in my output array.但是我只想要我的 output 数组中的 3 个项目。

I am looking to get我想得到

COMPONENT_IMAGES="img1:2.0.1, img2:1.4.0, img3:1.2.5"

What am I missing here?我在这里错过了什么? Thanks!谢谢!

map lets you filter each array item individually. map允许您单独过滤每个数组项。 Here, we descend to .image , and concatenate the value of .name , a literal colon ":" , and the value of .tag .在这里,我们下降到.image ,并将.name的值、文字冒号":".tag的值连接起来。 The mapped array can then be join ed with a glue string ", " .然后可以使用粘合字符串", " join映射数组。

jq -r '
  .definition.services
  | "COMPONENT_IMAGES=\"" + (map(.image | .name + ":" + .tag) | join(", ")) + "\""
'
COMPONENT_IMAGES="img1:2.0.1, img2:1.4.0, img3:1.2.5"

Demo演示


If you prefer using string interpolation , here's its equivalent:如果您更喜欢使用string interpolation ,这里是它的等价物:

jq -r '
  .definition.services
  | "COMPONENT_IMAGES=\"\(map(.image | "\(.name):\(.tag)") | join(", "))\""
' 
COMPONENT_IMAGES="img1:2.0.1, img2:1.4.0, img3:1.2.5"

Demo演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM