json array into json stream with jq

json array into json stream with jq

此任务与 类似,但就我而言,我想换一种方式。 所以说我们有输入:

[
    {
        "name": "John",
        "email": "john@company.com"
    },
    {
        "name": "Brad",
        "email": "brad@company.com"
    }
]

并且期望的输出是:

{
    "name": "John",
    "email": "john@company.com"
}
{
    "name": "Brad",
    "email": "brad@company.com"
}

我尝试编写一个 bash 函数,它将在循环中执行:

#!/bin/bash

json=`cat `
length=`echo $json | jq '. | length'`

for (( i=0; i<$length ; i++ ))
do
echo $json | jq ".[$i]"
done

但显然速度极慢...

有什么方法可以更好地使用 jq 吗?

你可以使用这个:

jq '.[]' file

如果您使用 .[index] 语法,但完全省略索引,它将 return 数组的所有元素。

测试:

$ jq '.[]' file
{
  "email": "john@company.com",
  "name": "John"
}
{
  "email": "brad@company.com",
  "name": "Brad"
}

您可以应用“.[]”过滤器。

本教程内容丰富 https://stedolan.github.io/jq/tutorial/