Search code examples
ansiblejinja2

How to flatten a list into items?


I'm trying to compare a createdDate value from 2 different sources, but one keeps being passed as a list. Here is what the object looks like:

{
  "changed": false,
  "failed": false,
  "object_info": [
    {
      "object_data": {
        "accept_ranges": "bytes",
        "content_length": 2760249,
        "content_type": "binary/octet-stream",
        "e_tag": "\\"0b82b2320d1d8ac226cd2720ccad554c\\"",
        "last_modified": "2023-05-15T16:32:27+00:00",
        "metadata": {
          "createddate": "2022-11-30T21:29:25.066Z"
        },
        "server_side_encryption": "AES256",
        "version_id": "SRehoPRyDbp.Rn2GKYXRE_40FzyLg4ek"
      }
    }
  ]
}

I want to compare the createddate value, but whenever I try to filter down to it, it's returned as a list. Here's the filter I'm using:

item_info.object_info | map(attribute='object_data.metadata.createddate')

It gets returned as this:

{
  "msg": [
    "2022-11-30T21:29:25.066Z"
  ]
}

I've tried adding | flatten to the end of the filter, but there's no change. I've also tried a litany of combinations of map and subelements at all different levels and none of them are working.

The object I'm comparing it to looks like this:

{
  "msg": "2022-11-30T21:29:25.066Z"
}

How do I get it to match?


Solution

  • The flatten filter transforms a list of nested lists into a flat list -- that is, you expect it to result in a list, so not what you're looking for here.

    If the result of item_info.object_info | map(attribute='object_data.metadata.createddate') is a list, and you want a scalar value, why not just ask for the first item in the list?

    item_info.object_info | map(attribute='object_data.metadata.createddate') | first