Dynamic JSON present/non-present object

What is the correct format for dynamic json when trying to insert an object that itself has dynamic json in it?

e.g.

{
  "foo": "bar",
  {{ switch.value ? {
      "a": {{ input.value }}
    } : undefined }}

If I try this, then I get errors about unmatched {

Hello,

I don't know if that is the whole JSON or the copied missed a line. The JSON is missing a closing }. In the image below, there is no } for the opening curly on line 1.

image

FYI, I would not recommend doing it that way. It's true that I do not know your use case. However, from a high level you're introducing additional unnecessary complexity. Whenever, you're using your JSON, you will have to check both if the key exists or not and if it's undefined. There are ways to make both checks in a single line from JS perspective so it's up to you how to handle it, like I've said I do not know your use case. Some clearer solutions:

One way is,

{
  "foo": "bar",
  "a": {{ input.value }}
}

you know "a" will always exists and the value is (assuming text input) blank or string value. Or possibly undefined based on how your app set up. If you need the check for switch.value then this below will cover it.

{
  "foo": "bar",
  "a": {{ switch.value ? input.value : undefined }}
}
1 Like

Sorry, yes it was quite late and I wasn't thinking clearly. So the way you've specified in your second solution is what I'm actually already doing, but the input.value itself also has nested dynamic json. Here is my full example

"usableCapacity": {{ usableCapacityOnOffSwitch.value ? {
    "unitPrefix": "{{usableCapacityUnit.value}}",
    "value": "{{usableCapacity.value}}",
    "unit": "Wh"
} : undefined }},

I could pull this all out into js, but then I'm unsure how to populate the json (json explorer) at runtime.

So that's why my example had the { "a": {{input.value}} } inside the template.

Never mind. I'm an idiot. I found the docs that state everything in {{}} is just js. I thought it was like mustache templating. Easy peasy, I can just reference the values without the braces. Thanks for the help everyone! That will teach me to work late at night.

2 Likes