json - 从命令行参数生成 JSON
问题描述
我想用 jq创建 JSON 输出,如下所示:
{
"records": [
{
"id": "1234",
"song": "Yesterday",
"artist": "The Beatles"
}
]
}
我以为我必须玩弄 jq 的“过滤器”,在阅读文档后我没有完全理解它的概念。
这是我到目前为止得到的:
$ 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"
}
]
}
我要修改过滤器吗?我要更改输入吗?
解决方案
您最初尝试的另一种方法,jq-1.6
您可以使用该$ARGS.positional
属性从头开始构造您的 JSON
jq -n '
$ARGS.positional | {
records: [
{
id: .[0],
song: .[1],
artist: .[2]
}
]
}' --args 1234 Yesterday "The Beatles"
至于为什么你最初的尝试没有奏效,看起来你根本没有修改你的 json,你的过滤器'.'
基本上只是读入并打印出“未触及”。使用设置的参数--arg
需要设置为过滤器内的对象。
推荐阅读
- wordpress - 在插件类中设置时撤消 add_action
- bash - 如何参考另一列中的匹配值从三个不同文件中添加两列?
- android - 校准重力和磁场传感器
- postgresql - Migrate PostgreSQL text/bytea column to large object?
- c# - 如果不存在,如何将datagridview行插入数据库,但如果存在更新,那么如果每一行都有相同的id?
- javascript - Why do I get this error in JavaScript React?
- vue.js - stretch embedded vimeo in vue.js fails
- java - 在 Android 中跨不同模块访问代码?
- java - 如何控制 JSeparator 的大小?
- html - How can line breaks be added to a data:text/plain URI?