用jq解析每行JSON记录? [英] Parsing JSON record-per-line with jq?
本文介绍了用jq解析每行JSON记录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个在每行输出JSON记录的工具,我想用jq
处理它.
I've got a tool that outputs a JSON record on each line, and I'd like to process it with jq
.
输出看起来像这样:
{"ts":"2017-08-15T21:20:47.029Z","id":"123","elapsed_ms":10}
{"ts":"2017-08-15T21:20:47.044Z","id":"456","elapsed_ms":13}
当我将其传递给jq
时,如下所示:
When I pass this to jq
as follows:
./tool | jq 'group_by(.id)'
...它输出一个错误:
...it outputs an error:
jq: error (at <stdin>:1): Cannot index string with string "id"
如何获取jq
来处理每行JSON记录数据?
How do I get jq
to handle JSON-record-per-line data?
推荐答案
使用--slurp
(或-s
)开关:
Use the --slurp
(or -s
) switch:
./tool | jq --slurp 'group_by(.id)'
它输出以下内容:
[
[
{
"ts": "2017-08-15T21:20:47.029Z",
"id": "123",
"elapsed_ms": 10
}
],
[
{
"ts": "2017-08-15T21:20:47.044Z",
"id": "456",
"elapsed_ms": 13
}
]
]
...然后可以进一步处理.例如:
...which you can then process further. For example:
./tool | jq -s 'group_by(.id) | map({id: .[0].id, count: length})'
这篇关于用jq解析每行JSON记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文