如何使用jq将JSON字符串格式化为表? [英] How to format a JSON string as a table using jq?
问题描述
刚开始使用Bash脚本,偶然发现jq可以使用JSON.
Just started out with Bash scripting and stumbled upon jq to work with JSON.
我需要将如下所示的JSON字符串转换为表格以在终端中输出.
I need to transform a JSON string like below to a table for output in the terminal.
[{
"name": "George",
"id": 12,
"email": "george@domain.com"
}, {
"name": "Jack",
"id": 18,
"email": "jack@domain.com"
}, {
"name": "Joe",
"id": 19,
"email": "joe@domain.com"
}]
我要在终端中显示的内容:
What I want to display in the terminal:
ID Name
=================
12 George
18 Jack
19 Joe
请注意我不想显示每一行的email属性,因此jq命令应该涉及一些过滤.下面为我提供了一个简单的名称和ID列表:
Notice how I don't want to display the email property for each row, so the jq command should involve some filtering. The following gives me a plain list of names and id's:
list=$(echo "$data" | jq -r '.[] | .name, .id')
printf "$list"
问题在于,我无法将其显示为表格.我知道jq有一些格式化选项,但是不如使用printf
时的选项好.我想我想在一个数组中获取这些值,然后可以遍历自己进行格式化...?我尝试过的事情给我带来了不同的结果,但从来没有我真正想要的.
The problem with that is, I cannot display it like a table. I know jq has some formatting options, but not nearly as good as the options I have when using printf
. I think I want to get these values in an array which I can then loop through myself to do the formatting...? The things I tried give me varying results, but never what I really want.
有人可以指出我正确的方向吗?
Can someone point me in the right direction?
推荐答案
为什么不这样:
echo '[{
"name": "George",
"id": 12,
"email": "george@domain.com"
}, {
"name": "Jack",
"id": 18,
"email": "jack@domain.com"
}, {
"name": "Joe",
"id": 19,
"email": "joe@domain.com"
}]' | jq -r '.[] | "\(.id)\t\(.name)"'
输出
12 George
18 Jack
19 Joe
要进行细粒度的格式化,请使用awk
Edit 1 : For fine grained formatting use tools like awk
echo '[{
"name": "George",
"id": 12,
"email": "george@domain.com"
}, {
"name": "Jack",
"id": 18,
"email": "jack@domain.com"
}, {
"name": "Joe",
"id": 19,
"email": "joe@domain.com"
}]' | jq -r '.[] | [.id, .name] | @csv' | awk -v FS="," 'BEGIN{print "ID\tName";print "============"}{printf "%s\t%s%s",$1,$2,ORS}'
ID Name
============
12 "George"
18 "Jack"
19 "Joe"
回复
我无法获取直接包含数组的变量 来自jq?
There's no way I can get a variable containing an array straight from jq?
为什么不呢?
一个涉及到示例(实际上是从您的示例修改而来的示例)中,将电子邮件更改为数组可以证明这一点
A bit involved example( in fact modified from yours ) where email is changed to an array demonstrates this
echo '[{
"name": "George",
"id": 20,
"email": [ "george@domain1.com" , "george@domain2.com" ]
}, {
"name": "Jack",
"id": 18,
"email": [ "jack@domain3.com" , "jack@domain5.com" ]
}, {
"name": "Joe",
"id": 19,
"email": [ "joe@domain.com" ]
}]' | jq -r '.[] | .email'
输出
[
"george@domain1.com",
"george@domain2.com"
]
[
"jack@domain3.com",
"jack@domain5.com"
]
[
"joe@domain.com"
]
这篇关于如何使用jq将JSON字符串格式化为表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!