【问题标题】:remove period from key name in JSON response从 JSON 响应中的键名中删除句点
【发布时间】:2017-07-31 04:18:43
【问题描述】:

所以,我不确定这里发生了什么以及为什么要在 JSON 键名中加上句点。

我正在尝试做的概述是通过 ejs 变量将 json 响应传递到页面模板中,并从中获取各个字段中的数据。

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

谢谢!

【问题讨论】:

  • 你试过product.data["product.imgone2"].value.main.url吗?
  • 括号符号 FTW!

标签: javascript json node.js express ejs


【解决方案1】:

你试过 product.data["product.imgone2"].value.main.url 吗?

来自官方文档

访问像object.property这样的属性

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

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

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

【讨论】:

    【解决方案2】:

    正如已经提到的,使用括号表示法:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-24
      • 1970-01-01
      • 2021-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多