展开大数组并选择JQ中的元素



由于流式/过滤JSON在概念上的工作方式,这可能是不可能的,但让我们假设我有以下JSON:

[
{
"name": "account_1",
"type": "account"
},
{
"name": "account_2",
"type": "account"
},
{
"name": "user_1",
"type": "user"
},
{
"name": "user_2",
"type": "user"
}
]

现在我只想打印出用户对象

我知道我可以过滤到像这样的流类型实体:

cat file.json | jq --stream 'select(.[0][1] == "type" and .[1] == "user" | .)'

将产生:

[
[
2,
"type"
],
"user"
]
[
[
3,
"type"
],
"user"
]

是否有任何方法可以打印出这些类型的父对象而不是类型实体?例:我想出去一下:

[
{
"name": "user_1",
"type": "user"
},
{
"name": "user_2",
"type": "user"
}
]

如果没有流,这是一个非常简单的练习。例如:

cat file.json | jq '.[] | select(.type=="user")'

在现实中,实际的输入文件大约是5GB,所以我需要使用流输入,但是我似乎无法在启用--stream的情况下获得jq语法。例如

cat file.json | jq --stream '.[] | select(.type=="user")'

生产:

jq: error (at <stdin>:3): Cannot index array with string "type"
jq: error (at <stdin>:5): Cannot index array with string "type"
...

(编辑以包含所需输出)

直接截断顶级数组

jq -n --stream 'fromstream(1 | truncate_stream(inputs)) | select(.type == "user")'
<<p><一口>

在线演示/一口>jqplay不支持——stream选项,所以上面的演示使用——stream的输出作为JSON输入。

最新更新