使用 jq 将过滤器生成的输出与静态 JSON 对象合并
Merging filter-generated output with static JSON object using jq
我正在尝试使用 jq
遍历一些带分隔符的文本文件,并从行中生成对象。
我还想在生成的结果中添加一些“静态”对象(json
shell 下面示例中的变量)。
我提出了以下解决方案,确实 产生了我想要的输出。但是,因为我对 jq 不是很有信心,所以每次用它解决问题时,感觉就像猴子敲打打字机,而不是精心设计的答案。所以,我想象这可能是不正确的。
data.txt
apple|fruit
Tesla|car
sparrow|bird
测试 (bash shell):
$ json='[
{ "object": "love", "type": "emotion" },
{ "object": "Ukraine", "type": "country" }
]'
$ jq --slurp --raw-input --argjson extra "$json" '
split("\n") |
map(select(length>0)) |
map(split("|") | {
object: .[0],
type: .[1]
}) as $data |
$data + $extra' data.txt
输出:
[
{
"object": "apple",
"type": "fruit"
},
{
"object": "Tesla",
"type": "car"
},
{
"object": "sparrow",
"type": "bird"
},
{
"object": "love",
"type": "emotion"
},
{
"object": "Ukraine",
"type": "country"
}
]
这样有效率吗?
我不知道它是否更有效,但您可以使用 --raw-input
或 -R
缩短代码,而不使用 --slurp
或 -s
以按行读取流原始文本(无需按换行符拆分),/
运算符在一行内进行“列”拆分,reduce
从“静态”开始连续构建最终结构数据。
jq -Rn --argjson extra "$json" '
reduce (inputs / "|") as [$object, $type] ($extra; . + [{$object, $type}])
' data.txt
如果你想要最后的“静态”数据,在后面添加它并从一个空数组开始:
jq -Rn --argjson extra "$json" '
reduce (inputs / "|") as [$object, $type] ([]; . + [{$object, $type}]) + $extra
' data.txt
你可以试试这个:
jq -nR --argjson extra "$json" '
[inputs / "|" | {object:.[0], type:.[1]}] + $extra' data.txt
[inputs / "|" | {object: .[0], type: .[1]}]
演示
https://jqplay.org/s/XkDdy9-lBq
或者
reduce (inputs / "|") as [$obj, $typ] ([]; .+[{$obj, $typ}])
演示
我正在尝试使用 jq
遍历一些带分隔符的文本文件,并从行中生成对象。
我还想在生成的结果中添加一些“静态”对象(json
shell 下面示例中的变量)。
我提出了以下解决方案,确实 产生了我想要的输出。但是,因为我对 jq 不是很有信心,所以每次用它解决问题时,感觉就像猴子敲打打字机,而不是精心设计的答案。所以,我想象这可能是不正确的。
data.txt
apple|fruit
Tesla|car
sparrow|bird
测试 (bash shell):
$ json='[
{ "object": "love", "type": "emotion" },
{ "object": "Ukraine", "type": "country" }
]'
$ jq --slurp --raw-input --argjson extra "$json" '
split("\n") |
map(select(length>0)) |
map(split("|") | {
object: .[0],
type: .[1]
}) as $data |
$data + $extra' data.txt
输出:
[
{
"object": "apple",
"type": "fruit"
},
{
"object": "Tesla",
"type": "car"
},
{
"object": "sparrow",
"type": "bird"
},
{
"object": "love",
"type": "emotion"
},
{
"object": "Ukraine",
"type": "country"
}
]
这样有效率吗?
我不知道它是否更有效,但您可以使用 --raw-input
或 -R
缩短代码,而不使用 --slurp
或 -s
以按行读取流原始文本(无需按换行符拆分),/
运算符在一行内进行“列”拆分,reduce
从“静态”开始连续构建最终结构数据。
jq -Rn --argjson extra "$json" '
reduce (inputs / "|") as [$object, $type] ($extra; . + [{$object, $type}])
' data.txt
如果你想要最后的“静态”数据,在后面添加它并从一个空数组开始:
jq -Rn --argjson extra "$json" '
reduce (inputs / "|") as [$object, $type] ([]; . + [{$object, $type}]) + $extra
' data.txt
你可以试试这个:
jq -nR --argjson extra "$json" '
[inputs / "|" | {object:.[0], type:.[1]}] + $extra' data.txt
[inputs / "|" | {object: .[0], type: .[1]}]
演示
https://jqplay.org/s/XkDdy9-lBq
或者
reduce (inputs / "|") as [$obj, $typ] ([]; .+[{$obj, $typ}])
演示