jq按优先级和条件获取第一个值

时间:2017-03-21 22:03:49

标签: json conditional-statements jq

我跟随json:

{
  "Detail": {
    "Response": [
      {
        "ID": "8000000D-1483989576",
        "Name": "",
        "FullName": "FullName 1"
      },
      {
        "ID": "8000000C-1483985849",
        "Name": "Name 1"
      },
      {
        "ID": "80000006-1481277410",
        "Name": "Name 2",
        "FullName": "FullName 2"
      },
      {
        "ID": "8000000B-1481537384",
        "Name": "Name 3"
      }
    ]
  }
}

我正在尝试创建另一个json,它将非空/非空.Name视为优先级,否则获取.FullName无论它是空还是空,最终的json将如下所示:

[
  {
    "id": "8000000D-1483989576",
    "name": "FullName 1"
  },
  {
    "id": "8000000C-1483985849",
    "name": "Name 1"
  },
  {
    "id": "80000006-1481277410",
    "name": "FullName 2"
  },
  {
    "id": "8000000B-1481537384",
    "name": "Name 3"
  }
]

我得到的临时解决方案是使用join

jq '[.Detail.Response[] | {id: .ID, name: [.Name, .FullName] | join("") }]'

但是,当然,只有当.FullName为空或为空时它才会起作用。

2 个答案:

答案 0 :(得分:2)

这应该可以帮助你:

.Detail.Response[]
| { id: .ID, Name: (if .Name != "" then .Name else .FullName end) }

答案 1 :(得分:1)

我找到了一种方法,可以使用XMLHttpRequest.prototypemap

select