JsonparsingJade

我想呈现我的JSON玉,我发送JSON数据,但是这给这样的错误

app.get('/showRequestAccepted',function(req,res){ Account.getFriends(req.user,{"friends.status":Status.Accepted},function(err,sonuc) { if(err) throw err //Json'i formatted göstermek için null ve 4 boşluk için else console.log(sonuc); res.render('profil',{sonuc:JSON.stringify(sonuc)}); }); }); 

在Jade中使用Jade来迭代JSON我发现这个例子不能帮助我

  each jsonObj in sonuc li=jsonObj.username 

我得到这个错误

  500 TypeError: /Users/ANTEGRUP/Desktop/passport-local-master/views/profil.jade:31 29| 30| div#userlist > 31| each jsonObj in sonuc 32| li=jsonObj.username 33| 34| Cannot read property 'length' of undefined 

我认为你是混淆JSON和JavaScript对象,基本上你的代码应该是这样的:

  app.get('/showRequestAccepted',function(req,res){ Account.getFriends(req.user,{"friends.status":Status.Accepted},function(err,sonuc) { if(err) throw err //Json'i formatted göstermek için null ve 4 boşluk için else console.log(sonuc); res.render('profil',{sonuc: sonuc)}); }); 

对于你的例子来说, sonuc必须是其中包含用户sonuc段的对象的数组。 在javascript对象字面表示法中,这将是一个例子: [{ username : 'a' }]

现在JSON,是一种数据交换格式。 当你做JSON.stringify(sonuc)时,你会得到一个代表该数组的string。 你可以用typeof JSON.stringify(sonuc) === 'string'来确认,它返回true。 但在这种情况下,我们需要一个对象数组,所以Array.isArray(sonuc)应该返回true,如果它是数组。

你可能会看看这个问题: JavaScript对象VS JSON