Terraform: [Question] How to convert string to list or map

Created on 7 Dec 2017  ·  9Comments  ·  Source: hashicorp/terraform

Hi there,

Terraform Version

Terraform v0.10.7

Question

I have a json string, like this:

{
    "key1":"value1",
    "key2":["value2-1","value2-2"],
    "key3":[{ "subkey1":"subvalue1"},{"subkey2","subvalue2"},{"....":"...."}]
}

I can get the key/value pair , but how to convert json string to list or map ?
Currently, I can convert a string to a list, using the split method, but is there a better way?
And how to convert string to map?

Thanks for any help!

Most helpful comment

in my code, I use External data source to convert a string to map. e.g: for string like {"key1":"value1","key2":"value2"}

data "external" "converer" {
  program = ["echo", "${var.str}"]
}

output "value1" {
  value = "${(lookup(data.external.converter.result, "key1")}"
}

The output would then be "value1".

All 9 comments

Hi @apparentlymart
I have a string , like this :
json {"key1":"value1","key2":"value2"}
Do you have solution for this scenario?
Please help me, Thanks

Hi @LanceNero,

At the moment there is no built-in way to decode a JSON string. There is some discussion about this in #10363, including information about our plans here.

In the mean time, it is necessary to pass data into Terraform some other way, such as generating a .tfvars file containing your value to access it via an input variable.

Hi @apparentlymart
Ok, got it
Thanks your reply

in my code, I use External data source to convert a string to map. e.g: for string like {"key1":"value1","key2":"value2"}

data "external" "converer" {
  program = ["echo", "${var.str}"]
}

output "value1" {
  value = "${(lookup(data.external.converter.result, "key1")}"
}

The output would then be "value1".

@oulydna is spot on, but I thought I would correct a few typos:

data "external" "converter" {
  program = ["echo", "${var.str}"]
}

output "value1" {
  value = "${lookup(data.external.converter.result, "key1")}"
}

If I saved someone 3 minutes, it's worth it 🎉

@timduly4 And @oulydna I get the error in powershell

* data.external.converter: 1 error(s) occurred:
* data.external.converter: data.external.converter: can't find external program "echo"

Any Idea what I do wrong?

@kism3t this indicates that you don't have echo on your machine-- are you on Windows? If so, you'll need to find the Windows equivalent...

I run on windows within poweshell. There I have echo command.

I'm going to lock this issue because it has been closed for _30 days_ ⏳. This helps our maintainers find and focus on the active issues.

If you have found a problem that seems similar to this, please open a new issue and complete the issue template so we can capture all the details necessary to investigate further.

Was this page helpful?
0 / 5 - 0 ratings