Nunjucks:我可以组合、连接或更新 JSON 对象吗?

问题描述

是否可以在 Nunjucks 中修改、更新、组合、连接或以其他方式连接 2 位 JSON?

这是一个示例:我正在尝试向现有变量添加一个元素。 (该元素可以作为空字符串存在,但我也找不到更新它的方法..)

鉴于此 JSON 结构:

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

然后我想添加以下 error 元素,所以我有

{
  type: "radio",text: "No"
    }
  ],error: {
    message: "Some message. This Could be empty to start with and updated somehow too"
  }
}

这是我设法得到的最接近的..

{# index.njk #}

{% set question = {
  type: "radio",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" } #}

解决方法

如果您可以在错误消息后创建问题,您可以执行以下操作:

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

...

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...