How to create a list of map objects within a JSON object using for....in loop

We are trying to create below mentioned JSON in terraform. Basically list of map objects
Currently we are trying to use forin loop which is iterating over a list of map (i.e. list(map(string)). Can someone please share some code for dynamically generating this list using inline for loop ?

{
    "MyApp": [
        {
            "key1": "value1" // this is the map object
        },
        {
            "key2": "value2" // this is another map object
        }
    ]
}

My code:

variable "my_list" {
  description = ""
  type        = list(map(string))
  default     = [
    {
       key = key1
       value = value1
    },
    {
       key = key2
       value = value2
    }
  ]
}

event_pattern =  jsonencode({
   "MyApp": [ for item in my_list : item["key"] => item["value"]]
})

This is throwing me syntax error '(', ']' or if expected, got '=>'. Can you please help me get the right way to achieving this JSON.

Thanks

Hi @gtwuser,

You are using a list comprehension, not a map, so you can’t use the => mapping syntax. I think you’re asking how to create a map for each value, in which case you need to use { and } for a map literal. The final piece is probably the key value, which must be wrapped in () so that it is evaluated rather than taken as a literal value.

Together that would look like:

event_pattern =  jsonencode({
   "MyApp": [ for item in var.my_list : {(item["key"]): item["value"]} ]
})
1 Like

Thank you so much, will give it a try and update back

@jbardin we facing another related issue now, I have raised a query for the same. Im not sure if its because of the above changes we made, but it should not be. Link for reference: LimitExceededException: The requested resource exceeds the maximum number allowed for AWS EB rules. I can confirm whether our solution works once this above issues is resolved.

Although my preceeding issue is not resolved, but your suggested answer worked. Thanks again.