将命令行参数生成JSON

3
我希望使用 jq 创建 JSON 输出,格式如下:
{
  "records": [
    {
      "id": "1234",
      "song": "Yesterday",
      "artist": "The Beatles"
    }
  ]
}

我觉得我需要调整jq的“filter”,但是在阅读了文档之后,我并没有完全理解它的概念。

目前为止,这是我所得到的内容:

$ 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"
    }
  ]
}

我需要修改过滤器吗?还是改变输入呢?

6个回答

8

jq-1.6中,除了使用原始方法外,您还可以使用$ARGS.positional属性从头构建JSON。

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

关于你的原始尝试为什么没有成功,看起来你根本没有修改你的json,使用你的过滤器'.',你基本上只是读入并打印出“未经触摸”的内容。使用—arg设置的参数需要设置为过滤器内的对象。

7
您正在寻找像这样的东西:
jq --null-input               \
   --arg id 1234              \
   --arg song Yesterday       \
   --arg artist "The Beatles" \
'.records[0] = {$id, $song, $artist}'

花括号之间的每个变量引用都会转换为一个键值对,其中它的名称是键,它的值是该键对应的值。将结果对象分配给.records[0]会强制创建其周围的结构。


2
jq  --null-input\
    --argjson id     1234\
    --arg     song   Yesterday\
    --arg     artist "The Beatles"\
    '{ "records" : [{ $id, $song, $artist }] }'

提供

{
  "records": [
    {
      "id": 1234,
      "song": "Yesterday",
      "artist": "The Beatles"
    }
  ]
}

1
我认为你把JSON和JQ弄反了:
这应该是你的JQ脚本:

rec.jq

{
  records: [
    {
      id: $id,
      song: $song,
      artist: $artist
    }
  ]
}

这应该是你的 JSON(空):

rec.json

{}

然后:

jq --arg id 123 --arg song "Yesterday" --arg artist "The Beatles" -f rec.jq rec.json

它会产生:

{
  "records": [
    {
      "id": "123",
      "song": "Yesterday",
      "artist": "The Beatles"
    }
  ]
}

1
从一个空的JSON开始,并添加缺失的部分:
$ jq --arg id 1234 \
     --arg song Yesterday \
     --arg artist "The Beatles" \
     '. | .records[0].id=$id | .records[0].song=$song | .records[0].artist=$artist' \
  <<<'{}'

输出

{
  "records": [
    {
      "id": "1234",
      "song": "Yesterday",
      "artist": "The Beatles"
    }
  ]
}

另一个更简洁的方法基于@Inian的答案,可以是:
jq -n \
   --arg id 1234
   --arg song Yesterday
   --arg artist "The Beatles"
   '{records: [{id:$id, song:$song, artist:$artist}]}'

0
jo可以构建数组和嵌套对象:
$ jo -p records[]="$(jo id=12345 song=Yesterday artist='The Beatles')"
{
   "records": [
      {
         "id": 12345,
         "song": "Yesterday",
         "artist": "The Beatles"
      }
   ]
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接