本文介绍了从命令行参数生成JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想用jq 创建JSON输出,如下所示:
I want to create JSON output with jq that looks like this:
{
"records": [
{
"id": "1234",
"song": "Yesterday",
"artist": "The Beatles"
}
]
}
我以为我不得不纠结jq的过滤器",在阅读文档后,我对它的概念还不完全了解.
I assumed I have to twiddle with the "filter" of jq whose concept I don't fully get after reading the doc.
这是我到目前为止得到的:
This is what I got so far:
$ jq --arg id 1234 \
--arg song Yesterday \
--arg artist "The Beatles" \
'.' \
<<<'{ "records" : [{ "id":"$id", "song":"$song", "artist":"$artist" }] }'
可打印
{
"records": [
{
"id" : "$id",
"song" : "$song",
"artist" : "$artist"
}
]
}
我是否修改过滤器?我要更改输入吗?
Do I modify the filter? Do I change the input?
推荐答案
您正在寻找这样的东西:
You are looking for something like this:
jq --null-input \
--arg id 1234 \
--arg song Yesterday \
--arg artist "The Beatles" \
'.records[0] = {$id, $song, $artist}'
大括号之间的每个变量引用都转换为一个键-值对,其名称是键,其值是值.并将结果对象分配给.records[0]
会强制创建周围的结构.
Each variable reference between curly brackets is converted to a key-value pair where its name is the key, and its value is the value. And assigning the resulting object to .records[0]
forces the creation of the surrounding structure.
这篇关于从命令行参数生成JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!