【问题标题】:Rendering json Object with express and jade - Can't access json fields使用express和jade渲染json对象-无法访问json字段
【发布时间】:2013-08-03 16:50:50
【问题描述】:

我的节点应用程序的相关 Express 部分:

/*Route to Product Views*/
app.get('/product/:id', function(req, res){
        Product.find({_id: req.params.id}, function (error, data) {
                if(error){
                        console.log(error);
                } else {
                        console.log("DATA :" + data); //correct json object
                        res.render('product',{
                                title: 'Product Template',
                                result: data
                                }
                        );
                }
        });

});

翡翠模板:

!!! 5
html
  head
    title #{title}
  body
    h1 #{result.name}
    h2 #{result.unitprice}
    p.
       #{result.description}
    h3 #{result}

因此,如果我访问http://myhost.com/product/51fa8402803244fb12000001,我看到的只是 h3 #{result} 的输出,即:

[{ 
__v: 0, 
_id: 51fa8402803244fb12000001, 
description: 'Awesome stuff you really need', 
discontinued: false, 
name: 'Some product', 
unitprice: 5.99 
}]

使用 JSON.stringify 没有区别,只是 h3 #{result} 返回“字符串化”的 JSON。 如何正确访问json字符串的字段?

【问题讨论】:

  • 兄弟,如果result是单文档数组,你不应该用result[0].nameresult[0].unitprice吗? console.log 打印什么?
  • 谢谢兄弟,如果 JSON.stringify() 被使用,它的工作原理就是这样!

标签: json node.js express pug


【解决方案1】:

您的数据库查询的输出以数组形式返回结果,因此您需要将数据作为数据[0] 发送到产品模板,以便您可以直接访问您需要作为结果[0] 访问的其他值。姓名等

/*Route to Product Views*/
app.get('/product/:id', function(req, res){
        Product.find({_id: req.params.id}, function (error, data) {
                if(error){
                        console.log(error);
                } else {
                        console.log("DATA :" + data[0]); //correct json object
                        res.render('product',{
                                title: 'Product Template',
                                result: data[0]
                                }
                        );
                }
        });

}) 

翡翠模板:

!!! 5
html
  head
    title #{title}
  body
    - product = typeof(result) != 'undefined' ? result : { }
    h1 #{product.name}
    h2 #{product.unitprice}
    p.
       #{product.description}
    h3 #{product}

【讨论】:

  • 即使c.P.u之前已经回答过这个问题,你的答案是正确的;)
  • 你好如何在客户端javascript中访问产品?
猜你喜欢
  • 2013-04-19
  • 2014-01-02
  • 2017-04-09
  • 2017-10-20
  • 2014-01-15
  • 2012-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多