报告每个(可选)子元素

时间:2018-06-29 02:00:08

标签: jq

想解析以下内容:

{
  "issues": [
    { "id": "1", "fields": { "links": [] } },
    { "id": "2", "fields": { "links": [ { "inlink": { "id": "red" } } ] } },
    { "id": "3", "fields": { "links": [ { "outlink": { "id": "yellow" } } ] } },
    { "id": "4", "fields": { "links": [ { "inlink": { "id": "green" } }, { "outlink": { "id": "blue" } } ] } }
  ]
}

将代表links元素的元素一一对应,如下所示(请注意,缺少id 1,而id 4出现了两次:

  { "id": "2", "link": { "linktype": "inlink", "id": "red" } },
  { "id": "3", "link": { "linktype": "outlink", "id": "yellow" } },
  { "id": "4", "link": { "linktype": "inlink", "id": "green" } },
  { "id": "4", "link": { "linktype": "outlink", "id": "blue" } }

以下jq分别适用于inlinkoutlink

.issues[] | .id as $id | .fields.links[] | .inlink.id as $lid | {$id,$lid}

给予

{ "id": "2", "lid": "red" }
{ "id": "3", "lid": null }
{ "id": "4", "lid": "green" }
{ "id": "4", "lid": null }

但无法弄清楚如何同时跟踪两种类型或引入键linktype。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

jq 解决方案:

jq -c '.issues[] | .id as $id
       | .fields.links[] | to_entries[]
       | {"id": $id, "link": {"linktype": .key, "id": .value.id}}' file

输出:

{"id":"2","link":{"linktype":"inlink","id":"red"}}
{"id":"3","link":{"linktype":"outlink","id":"yellow"}}
{"id":"4","link":{"linktype":"inlink","id":"green"}}
{"id":"4","link":{"linktype":"outlink","id":"blue"}}