从命令行参数生成 JSON

tow*_*owi 3 bash json jq

我想用 jq创建 JSON 输出如下所示:

{
  "records": [
    {
      "id": "1234",
      "song": "Yesterday",
      "artist": "The Beatles"
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

我认为我必须摆弄 jq 的“过滤器”,在阅读文档后我没有完全理解它的概念。

这是我到目前为止得到的:

$ jq --arg id 1234 \
     --arg song Yesterday \
     --arg artist "The Beatles" \
  '.' \
  <<<'{ "records" : [{ "id":"$id", "song":"$song", "artist":"$artist" }] }'
Run Code Online (Sandbox Code Playgroud)

哪个打印

{
  "records": [
    {
      "id" : "$id",
      "song" : "$song",
      "artist" : "$artist"
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

我要修改过滤器吗?我要更改输入吗?

Ini*_*ian 7

您最初尝试的另一种方法,jq-1.6您可以使用该$ARGS.positional属性从头开始构建您的 JSON

jq -n '
  $ARGS.positional | { 
    records: [ 
      { 
        id:     .[0], 
        song:   .[1], 
        artist: .[2]   
      }
    ] 
  }' --args 1234 Yesterday "The Beatles" 
Run Code Online (Sandbox Code Playgroud)

至于为什么你最初的尝试没有奏效,看起来你根本没有修改你的json,你的过滤器'.'基本上只是读入并打印出“原封不动”。设置 using 的参数--arg需要设置为过滤器内的对象。


ogu*_*ail 5

你正在寻找这样的东西:

jq --null-input               \
   --arg id 1234              \
   --arg song Yesterday       \
   --arg artist "The Beatles" \
'.records[0] = {$id, $song, $artist}'
Run Code Online (Sandbox Code Playgroud)

大括号之间的每个变量引用都转换为键值对,其中名称是键,值是值。并将生成的对象分配给.records[0]强制创建周围的结构。