遍历字典jq-Shell [英] Iterate through dictionaries jq - shell

查看:151
本文介绍了遍历字典jq-Shell的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的JSON

{
  "images" : [
    {
      "size" : "29x29",
      "idiom" : "iphone",
      "filename" : "Icon-Small@2x.png",
      "scale" : "2x"
    }
     ......
     ......
    {
      "size" : "60x60",
      "idiom" : "iphone",
      "filename" : "Icon-60@3x.png",
      "scale" : "3x"
    }
  ],
  "info" : {
    "version" : 1,
    "author" : "xcode"
  }
}

我想遍历images数组中的每个字典. 为此我写了

I want to iterate through each dictionary in images array. For that I wrote

declare -a images=($(cat Contents.json | jq ".images[]"))
for image in "${images[@]}"
do
    echo "image --$image"
done

我期望输出的结果是每个字典都在重复打印.那是

I am expecting output that each dictionary is printing in an iteration. That is

image --{
  "size" : "29x29",
  "idiom" : "iphone",
  "filename" : "Icon-Small@2x.png",
  "scale" : "2x"
}
image --{
  "size" : "29x29",
  "idiom" : "iphone",
  "filename" : "Icon-Small@3x.png",
  "scale" : "3x"
}
image --{
  "size" : "40x40",
  "idiom" : "iphone",
  "filename" : "Icon-Spotlight-40@2x.png",
  "scale" : "2x"
}

但是它遍历每个字典中的每个元素,就像

But its iterating through each and every single elements in each dictionary like

image --{
image --"size":
image --"29x29",
image --"idiom":
image --"iphone",
image --"filename":
....
....
....

我的代码有什么问题

推荐答案

您的代码存在的问题是bash中的数组初始化看起来像这样:

The problem with your code is that an array initialization in bash looks like this:

declare -a arr=(item1 item2 item3)

项目之间用空格或换行符分隔.您还可以使用:

Items are separated by space or newline. You can also use:

declare -a arr(
    item1
    item2
    item3
)

但是,示例中的jq输出同时包含空格和换行符,这就是为什么报告的行为符合预期的原因.

However, the jq output in the example contains both spaces and newlines, that's why the reported behaviour is as expected.

解决方法:

我首先要获取密钥,将其通过管道传递到读取循环,然后为列表的每个项目调用jq:

I would get the keys first, pipe them to a read loop and then call jq for each item of the list:

jq -r '.images|keys[]' Contents.json | while read key ; do
    echo "image --$(jq ".images[$key]" Contents.json)"
done

如果您不喜欢漂亮的打印,也可以使用以下jq命令:

You can also use this jq command if you don't care about pretty printing:

jq -r '.images[]|"image --" + tostring' Contents.json


要访问子数组的某些属性,可以使用:


To access a certain property of the subarray you can use:

jq -r '.images|keys[]' Contents.json | while read key ; do
    echo "image --$(jq ".images[$key].filename" Contents.json)"
done

例如,上面的节点将为每个节点打印filename属性.

The above node will print the filename property for each node for example.

但是,仅使用jq可以将其表达得更加简单:

However this can be expressed much simpler using jq only:

jq -r '.images[]|"image --" + .filename' Contents.json

或更简单:

jq '"image --\(.images[].filename)"' Contents.json

这篇关于遍历字典jq-Shell的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆