Magnus Våge
Magnus Våge

Reputation: 305

How to use a dynamic list key in Liquid statements

I have a very basic Liquid problem, and can't really find an answer that fits the bill for me.

Assume I have two objects:

data = {
   "key1": "somevalue",
   "key2": someothervalue"
}

and

mapping = {
   "mapping1": "key1"
}

I want to print a value from data using the key from mapping. What I have tried is:

{{data[mapping.mapping1]}}

Which I would expect to print somevalue

If I change mapping1 to key2, I would expect my Liquid statement to print someothervalue

Where am I going wrong?

Upvotes: 1

Views: 1109

Answers (1)

JHeth
JHeth

Reputation: 8346

Your objects are not valid JSON, maybe this is your issue? If you were using valid JSON the index accessing with square brackets you showed above would work in Liquid.

Here's what a valid JSON object would look like:

{
  "data": {
    "key1": "somevalue",
    "key2": "someothervalue"
  },
  "mapping": {
    "map1": "key2"
  }
}

In which case {{data[mapping.map1]}} would produce someothervalue.

You can test it out in this Liquid Sandbox just add the Liquid tag in the template field, and the JSON above in the Source JSON field and then switch back to the template field and you will see the proper output.

enter image description here

Upvotes: 0

Related Questions