首页 > 解决方案 > 从命令行参数生成 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"
    }
  ]
}

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

标签: jsonbashjq

解决方案


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

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

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


推荐阅读