Andrew
Andrew

Reputation: 13221

Nunjucks: Can I combine, concatenate or update a JSON object?

Is it possible to amend, update, combine, concatenate or otherwise join 2 bits of JSON in Nunjucks?

Here's an example: I'm trying to add an element to an existing variable. (The element can exist as an empty string, but I can't find a way to update that either..)

Given this JSON stucture:

{
  type: "radio",
  items: [
    {
      value: "yes",
      text: "Yes"
    },
    {
      value: "no",
      text: "No"
    }
  ]
}

I then want to add the following error element so I have:

{
  type: "radio",
  items: [
    {
      value: "yes",
      text: "Yes"
    },
    {
      value: "no",
      text: "No"
    }
  ],
  error: {
    message: "Some message. This could be empty to start with and updated somehow too"
  }
}

This is the closest I've managed to get..

{# index.njk #}

{% set question = {
  type: "radio",
  items: [
    {
      value: "yes",
      text: "Yes"
    },
    {
      value: "no",
      text: "No"
    }
  ]
}
%}

{{ question | dump }}

<hr>

{# now I want to add or update a value in that JSON variable.. #}
{% set question = question + {
  error: {
    message: "some error message"
  }
}
%}

{{ question | dump }}

{# outputs: "[object Object][object Object]" #}
{# desired output: { "type": "radio" .... , "error": "some error message" } #}

Upvotes: 0

Views: 1188

Answers (1)

Andrew
Andrew

Reputation: 13221

You can do the following if you can create the question after the error message:

{% set errorMessage = { message: "some error message" } %}

...

{% set question = {
  type: "radio",
  items: [
    {
      value: "yes",
      text: "Yes"
    },
    {
      value: "no",
      text: "No"
    }
  ],
  error: errorMessage
}
%}

Upvotes: 1

Related Questions