2017-03-10 111 views
0

因此,我不确定这里发生了什么,以及为什么要在JSON键名称中输入一段时间。从JSON响应中的键名称中删除句号

我想要做的事情的概述是通过ejs变量传递json响应到页面模板中,并从个别字段中获取数据。

JSON响应看起来是这样的:

JSON tree

这是一个从prismic.io。 (打开对象支架被切断,数据是主对象的子对象)。

当我通过EJS

<%= product.data.product.imgone2.value.main.url %> 

注入我得到这样一个错误:

Cannot read property 'imgone2' of undefined 

哪,为什么会prismic做到这一点?

有没有办法解决与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); 
    }); 
}); 

谢谢!

+4

您是否尝试过'product.data [“product.imgone2”] .value.main.url'? – Hamms

+1

括号符号FTW! – epascarello

回答

2

您是否尝试过product.data [“product.imgone2”] .value.main.url?

从官方文档

要访问像object.property

属性的属性必须是有效的JavaScript标识,即字母数字字符的序列,也包括下划线(“_ “)和美元符号(”$“),不能以数字开头。例如,对象。$ 1是有效的,而object.1不是。

如果该属性不是有效的JavaScript标识符,则必须使用括号表示法。

https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Operators/Property_Accessors

0

因为它已经提到,使用括号表示法:

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; 
 
    }, {}); 
 
}