所以,我不知道这里发生了什么,以及为什么要在JSON键名中添加句号。
我要做的是将json响应通过ejs变量传递到页面模板中,并从各个字段中获取数据。
json的响应如下:

是prismic.io寄来的。(打开的对象括号在那里被切断,数据是主对象的子对象)。
当我通过EJS注射时
<%= 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);
});
});谢谢!
发布于 2017-03-10 00:36:09
你试过product.data"product.imgone2".value.main.url吗?
从官方文件上
访问像object.property这样的属性
属性必须是有效的JavaScript标识符,即字母数字字符序列,也包括不能以数字开头的下划线("_")和美元符号("$")。例如,object.$1有效,object.1无效。
如果属性不是有效的JavaScript标识符,则必须使用括号表示法。
发布于 2017-03-10 01:37:00
如前所述,使用括号表示法:
product.data["product.imgone2"].value.main.url如果由于任何原因这是不可能的,您可以通过以下函数运行对象来“修复”结构:
//this will transform structures like these:
var a = {
"data": {
"product.imgone2": {
"value": {
"main.url": "yourMainUrl"
},
"another.value": "to show how this is handled"
}
}
}
//into these:
var b = nestKeysWithDots(a);
console.log(JSON.stringify(b, null, 2));
//wich now can be resolved by your paths, without worrying
console.log(
"b.data.product.imgone2.value.main.url",
b.data.product.imgone2.value.main.url
);
//and the implementation:
function isObject(value){
return typeof value === "object" && value !== null;
}
function nestKeysWithDots(source){
return !isObject(source)? source:
Array.isArray(source)? source.map(nestKeysWithDots):
Object.keys(source).reduce((target, path) => {
var value = nestKeysWithDots(source[path]);
path.split(".").reduce((obj, key, index, array) => {
if(index+1 === array.length){
//last key
obj[key] = value;
return;
}
return key in obj && isObject(obj[key])?
obj[key]:
(obj[key] = {});
}, target);
return target;
}, {});
}
https://stackoverflow.com/questions/42707905
复制相似问题