在jq中将字符串字段拆分为数组?

lee*_*d00 6 json jq

我有一个从 curl 返回的 JSON 数组,如下所示:

[
 {
   "title": "Some Title",
   "tags":"tagA tag-B tagC"
 },
 {
   "title": "Some Title 2",
   "tags":"tagA tagC"
 },
 ...
]
Run Code Online (Sandbox Code Playgroud)

我想把它转换成...

[
 {
   "title": "Some Title",
   "tags":["tagA",
           "tag-B",
           "tagC"]
 },
 {
   "title": "Some Title 2",
   "tags":["tagA", 
           "tagC"]
 },
 ...
]
Run Code Online (Sandbox Code Playgroud)

到目前为止,我有:

(map(select(.tags!=null)) | map(.tags | split(" "))) as $tags | $tags

这似乎给了我类似的东西:

     [
      [
       "tagA",
       "tag-B",
       "tagC"
      ],
      [
       "tagA", 
       "tagC"
      ]
     ]
Run Code Online (Sandbox Code Playgroud)

但是我似乎无法将其编织回输出中,该输出将.tags作为原始对象中的数组提供给我,并具有原始值...

Sat*_*ura 14

你让它变得比现在复杂得多。只需使用map()|=

jq 'map(.tags |= split(" "))' file.json
Run Code Online (Sandbox Code Playgroud)

编辑:

如果您想在没有 的情况下处理条目tags

jq 'map(try(.tags |= split(" ")))' file.json
Run Code Online (Sandbox Code Playgroud)

或者,如果您想保持所有条目不变而没有tags

jq 'map(try(.tags |= split(" ")) // .)' file.json
Run Code Online (Sandbox Code Playgroud)

结果:

jq 'map(try(.tags |= split(" ")))' file.json
Run Code Online (Sandbox Code Playgroud)