所以,我不确定这里发生了什么以及为什么要在 JSON 键名称中添加句点。
我想要做的概述是将 json 响应通过 ejs 变量传递到页面模板中,并从中获取各个字段中的数据。
json 响应如下所示:
来自 prismic.io。 (打开的对象括号在那里被切断,数据是主对象的子对象)。
当我通过EJS注入(inject)时
<%= product.data.product.imgone2.value.main.url %>
我收到如下错误:
Cannot read property 'imgone2' of undefined
为什么棱镜要这样做?
有没有办法用 EJS 解决这个问题?
如果没有,我如何使用 JavaScript 函数解析 JSON 响应来删除它?
如果您需要我的路线:
router.get('/product/:slug', function(req, res) {
//route params
var slug = req.params.slug;
var productResp; //scope up api response to pass to render()
console.log(slug);
//api call
Prismic.api("https://prismic.io/api").then(function(api) {
return api.getByUID('product' , slug);
}).then(function(response) {
res.render('product-template', {
product: response,
})
}, function(err) {
console.log("Something went wrong: ", err);
});
});
谢谢!
最佳答案
have you tried product.data["product.imgone2"].value.main.url?
来自官方文档
访问诸如object.property
之类的属性
property must be a valid JavaScript identifier, i.e. a sequence of alphanumerical characters, also including the underscore ("_") and dollar sign ("$"), that cannot start with a number. For example, object.$1 is valid, while object.1 is not.
如果该属性不是有效的 JavaScript 标识符,则必须使用括号表示法。
https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Operators/Property_Accessors
关于javascript - 从 JSON 响应中的键名称中删除句点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42707905/