javascript - 从 JSON 响应中的键名称中删除句点

标签 javascript json node.js express ejs

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

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

json 响应如下所示:

JSON tree

来自 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/

相关文章:

javascript - 如果将脚本动态添加到 DOM, "async"属性/属性是否有用?

java - 如何在 Java 中将包含字符串列表的 JsonNode 转换为逗号分隔的字符串

c# - JSON .net 数组外的多个对象

javascript - Node.js 类递归发射

javascript - 如何将 webpack 文件加载器与 three.js 一起使用?

javascript - 不要让在输入中写入大于 max 属性的数字

javascript - 如何使用 json 数组映射序列和数据点

c# - 将Json作为ActionResult返回不会让异常消息通过

node.js - 我如何使用sequelize-typescript从单个字段引用多个模型?

node.js - 使用 rethinkDB 打开更少的连接