Tokens and Fn.jsondecode in Java


The output values of an existent CloudFormation stack I am working with are in JSON format.
I would like to extract a certain key from this JSON value.
I have used DataAwsCloudformationStack and I can get a specific value from the outputs of the stack using stack.outputs(“key”)
If I print it out, obviously it’s a token ${TfToken[TOKEN.156]}
Is there any way to parse this token which is a JSON and extract a value from it by key or path, similar to Jackson?
I can see that the Token class has methods like Token.asNumber or Token.asList, but they don’t seem to fit my use case.
Maybe Token.asAny could work, but could someone provide an example of how it can be used?
My cdktf project is written in Java.

Mircea Stan

I tried to use Fn.lookup to get by key from a map, but it is not working.
It’s probably related to the issue described here lookup fails on a JSON input · Issue #16154 · hashicorp/terraform · GitHub
I have limited knowledge about the type system of Terraform, but to me it looks like jsondecode returns a map.
I don’t know how to translate the square brackets notation to Java.

I think you’ll need to combine functions to get the desired outcome. Something like:

Fn.lookup(Fn.jsondecode(stack.outputs("key")), "jsonKey", "default")

This is in line with what I tried, but it is not working.

The following works in the Terraform console:

lookup(lookup(jsondecode("{“topic”:{“name”:“topic name”, “arn”:“topic arn”}}"), “topic”, “”), “arn”, “”)
“topic arn”

My Java code is:

arn = Token.asString(
Fn.lookup(stack.outputs(“key”), “topic”, “”),
“arn”, “”

which throws the following error when diff-ing the stack:

│ Invalid value for “inputMap” parameter: lookup() requires a map as the
│ first argument.
│ Error: Invalid function argument
│ “${lookup(lookup(data.aws_cloudformation_stack.cloudformationstacklookup.outputs[“key”], “topic”, “”), “arn”, “”)}”

You are missing the jsondecode call.

That’s such a rookie mistake, thanks for pointing it out.
In the end I have a method that looks up a certain path in JSON and retrieves the value:

private String getToken(String jsonToken, String... keys) {
    var token = Fn.jsondecode(jsonToken);

    for(String key : keys) {
        token = Fn.lookup(token, key, "");

    return Token.asString(token);

and it works like a charm.