jq - 在处理数组中的行时打印换行符

问题描述 投票:0回答:3

假设我有一个像这样的json:

{
  "records": [
    {
        "id": 1,
        "name": "hello"
    },
    {
        "id": 2,
        "name": "world"    
    }
  ]
}

我可以这样做:

$ jq -r '.records[] | "id: \(.id) name: \(.name)"' afile.json
id: 1 name: hello
id: 2 name: world

如何插入新行才能得到这个:

id: 1
name: hello

id: 2
name: world
json jq
3个回答
2
投票

另一种选择是使用

map()
join("\n\n")
结合使用,在每次迭代之间插入
\n
。这样就不会出现尾随换行符:

jq -rj '.records | map("id: \(.id)\nname: \(.name)") | join("\n\n")' input.json
id: 1
name: hello

id: 2
name: world

--raw-output
/
-r
:

使用此选项,如果过滤器的结果是字符串,那么它将直接写入标准输出,而不是格式化为带引号的 JSON 字符串。这对于使 jq 过滤器与非基于 JSON 的系统对话非常有用。

--join-output
/
-j
:

-r
但 jq 不会在每次输出后打印换行符。


2
投票

多种方法之一就是简单地将

\n
添加到字符串规范的末尾。

如果不需要末尾的额外换行符,您可以使用

sed '$d'
来删除它。


0
投票

这个呢?我只是将输出字符串分成几部分,并添加了一个额外的空过滤器“”以获得空行。

jq -r '.records[] |  "id: \(.id)", "name: \(.name)", ""' afile.json
© www.soinside.com 2019 - 2024. All rights reserved.