如何使用bash操纵jq输出? [英] How to manipulate a jq output using bash?

查看:68
本文介绍了如何使用bash操纵jq输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下jq代码段:

https://jqplay.org/s/QzOttRHoz1

我想使用bash循环结果数组中的每个元素,如伪代码所示:

I want to loop each element from the result array using bash such as the pseudo code shows:

#!/bin/bash
foreach result
  print "My name is {name}, I'm {age} years old"
  print "--"

结果将是:

My name is A, I'm 1 years old.
---
My name is B, I'm 2 years old.
---
My name is C, I'm 3 years old.
---

当然,这是一个简单的示例,只是为了阐明我的目标是从jq结果中分别操纵每个数组.

Of course this is a trivial example just to clarify that my goal is to manipulate each array from the jq result individually.

关于如何将伪代码写入有效的bash语句的任何建议?

Any suggestions on how to write the pseudo code into valid bash statements?

推荐答案

保存json:

{
    "Names": [
        { "Name": "A", "Age": "1" },
        { "Name": "B", "Age": "2" },
        { "Name": "C", "Age": "3" }
    ]
}

/tmp/input.txt我可以运行:

as /tmp/input.txt I can run:

</tmp/input.txt jq --raw-output 'foreach .Names[] as $name ([];[];$name | .Name, .Age )' \
| while read -r name && read -r age; do 
      printf "My name is %s, I'm %d years old.\n" "$name" "$age"; 
      printf -- "--\n";
done

带有 |的-原始输出.Name,.Age 仅对每个.Names数组成员打印两行,一个带有name,另一个带有age.然后,我在阅读&&的同时使用一次阅读了两行阅读,并使用它来遍历它们.

The --raw-output with | .Name, .Age just prints two lines per .Names array member, one with name and another with age. Then I read two lines at a time with while read && read and use that to loop through them.

如果您愿意:

["A","1"]
["B","2"]
["C","3"]

可悲的是,最好的办法是编写一个完整的解析器,该解析器将考虑诸如"\""之类的字符串.无论如何,您可以:

that's sad, the best would be to write a full parser that would take strings like "\"" into account. Anyway then you can:

</tmp/input2.txt sed 's/^\[//;s/\]$//;' \
| while IFS=, read name age; do 
       name=${name%\"}; 
       name=${name#\"};   
       age=${age%\"};
       age=${age#\"};
       printf "My name is %s, I'm %d years old.\n" "$name" "$age";
       printf -- "--\n";
done

第一个sed删除了每一行的开头和结尾的 [] .然后,我读取了两个用分隔的字符串(因此,诸如"a,b","c,d" 之类的var会被错误地读取).然后,除去这两个字符串的开头和结尾的".然后使用通常的printf来输出结果.

The first sed removed the leading and enclosing [ and ] in each line. Then I read two strings separated by , (so vars like "a,b","c,d" will be read incorrectly). Then these two strings are stripped of leading and enclosing ". Then the usuall printf is used to output the result.

这篇关于如何使用bash操纵jq输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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