问题描述
是否可以在 Nunjucks 中修改、更新、组合、连接或以其他方式连接 2 位 JSON?
这是一个示例:我正在尝试向现有变量添加一个元素。 (该元素可以作为空字符串存在,但我也找不到更新它的方法..)
鉴于此 JSON 结构:
{
type: "radio",items: [
{
value: "yes",text: "Yes"
},{
value: "no",text: "No"
}
]
}
{
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
}
%}