简体   繁体   English

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

[英]jq - print newlines while processing rows from an array

Suppose I have a json like this:假设我有一个这样的 json:

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

I could do this:我可以这样做:

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

How can I insert new lines so that I could get this:我怎样才能插入新行,这样我就可以得到这个:

id: 1
name: hello

id: 2
name: world

One of many ways would be simply to add \n to the end of the string specification.许多方法之一是简单地将\n添加到字符串规范的末尾。

If the extra newline at the end is unwanted, you could, for example, use sed '$d' to remove it.如果不需要末尾的额外换行符,您可以使用sed '$d'将其删除。

Another option is to use map() combined with join("\n\n") to insert an \n between each iteration.另一种选择是结合使用map()join("\n\n")在每次迭代之间插入一个\n This way there won't be a trailing newline:这样就不会有尾随换行符:

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

id: 2
name: world

--raw-output / -r : --raw-output / -r

With this option, if the filter's result is a string then it will be written directly to standard output rather than being formatted as a JSON string with quotes.使用此选项,如果过滤器的结果是字符串,则它将直接写入标准 output,而不是格式化为带引号的 JSON 字符串。 This can be useful for making jq filters talk to non-JSON-based systems.这对于使 jq 过滤器与非基于 JSON 的系统对话很有用。

--join-output / -j : --join-output / -j :

Like -r but jq won't print a newline after each output.-r类似,但 jq 不会在每个 output 之后打印换行符。

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

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