如何让 jq 在层次结构深处设置值?

How do I get jq to set values deep in the hierarchy?

我有很多文档如下所示,我需要更改 permanentLocation.id 并识别所有 id 为 null 的循环注释并将它们设置为 uuid

  {
  "circulationNotes": [
    {
      "id": null,
      "noteType": "Check in",
      "note": "Original location pmgd1 Gov. Documents - 2nd Fl.",
      "staffOnly": true,
      "source": {
        "id": "affd2a52-2f04-40e3-8da3-37c2de08e338",
        "personal": {
          "lastName": "Data",
          "firstName": "Migration"
        }
      },
      "date": null
    },
    {
      "id": null,
      "noteType": "Check out",
      "note": "Original location pmgd1 Gov. Documents - 2nd Fl.",
      "staffOnly": true,
      "source": {
        "id": "affd2a52-2f04-40e3-8da3-37c2de08e338",
        "personal": {
          "lastName": "Data",
          "firstName": "Migration"
        }
      },
      "date": null
    }
  ],
  "permanentLoanType": {
    "id": "cf424b8f-ae2b-4d01-8365-b412c7815ba9",
    "name": "PML 1st Fl. - Circulating"
  }
}

我可以在文档中轻松设置permanentLocation.id

jq  '(.permanentLocation.id = "1d0ec5e4-ba80-4eb9-8b0c-53da40d6335b")'

但是,当我尝试为 circ notes 设置一个 ids 时,它们是 null

jq --arg CHECKIN $(uuidgen)  '
(.permanentLocation.id = "1d0ec5e4-ba80-4eb9-8b0c-53da40d6335b")
| (.circulationNotes[] |(select(.noteType == "Check in" and .id == null) | .id = $CHECKIN ))'
{
  "id": "4b1e8cef-c0e7-44b3-9228-553f99019aa4",
  "noteType": "Check in",
  "note": "Original location pmgd1 Gov. Documents - 2nd Fl.",
  "staffOnly": true,
  "source": {
    "id": "affd2a52-2f04-40e3-8da3-37c2de08e338",
    "personal": {
      "lastName": "Data",
      "firstName": "Migration"
    }
  },
  "date": null
}

我只是匹配了第一个音符,而不是像 permanentLocation.id 那样修改值。

如何在返回完整文档时设置 .circulationNotes.id uuid(或任意数量的元素),这样我得到:

{
  "circulationNotes": [
    {
      "id": bd5379f7-69fc-48f5-8461-8dcc59883ae0,
      "noteType": "Check in",
      "note": "Original location pmgd1 Gov. Documents - 2nd Fl.",
      "staffOnly": true,
      "source": {
        "id": "affd2a52-2f04-40e3-8da3-37c2de08e338",
        "personal": {
          "lastName": "Data",
          "firstName": "Migration"
        }
      },
      "date": null
    },
    {
      "id": 33f60901-33a8-43d1-a2ce-e22d8be87d15,
      "noteType": "Check out",
      "note": "Original location pmgd1 Gov. Documents - 2nd Fl.",
      "staffOnly": true,
      "source": {
        "id": "affd2a52-2f04-40e3-8da3-37c2de08e338",
        "personal": {
          "lastName": "Data",
          "firstName": "Migration"
        }
      },
      "date": null
    }
  ],
  "permanentLoanType": {
    "id": "cf424b8f-ae2b-4d01-8365-b412c7815ba9",
    "name": "PML 1st Fl. - Circulating"
  },
  "permanentLocation": {
    "id": "1d0ec5e4-ba80-4eb9-8b0c-53da40d6335b"
  }
}

尝试

jq --arg CHECKIN $(uuidgen)  '(.permanentLocation.id = "1d0ec5e4-ba80-4eb9-8b0c-53da40d6335b")| (.circulationNotes[] |(select(.noteType == "Check in" and .id == null) | .id)) = $CHECKIN'