简体   繁体   English

在Jade中解析JSON

[英]Parsing JSON within Jade

I have a big array of objects that I am passing via express into a Jade template. 我有很多对象,我通过express传递给Jade模板。 It looks like this: 它看起来像这样:

[{ big object }, { big object }, { big object }, ...]

I pass it into the Jade template by stringifying it: 我通过字符串化将它传递给Jade模板:

res.render('search-results', {
  data: JSON.stringify(body)
});

In my Jade template, I am trying to parse the JSON and iterate over each object within, as follows: 在我的Jade模板中,我试图解析JSON并迭代其中的每个对象,如下所示:

each d, i in JSON.parse(data)
  // Do stuff

However, d is logged as [object Obj] when I print it, and I am thus unable to access to object. 但是,当我打印时, d被记录为[object Obj] ,因此我无法访问对象。 When I try to do JSON.parse(d) , it also fails because d is literally the string "[object Obj]". 当我尝试执行JSON.parse(d) ,它也会失败,因为d实际上是字符串“[object Obj]”。 I've tried passing the data into the template a bunch of different ways and keep coming up short. 我已经尝试过将这些数据传递到模板中,并采用不同的方式。 Any ideas? 有任何想法吗?

Fixed by doing the following: 通过执行以下操作来修复:

When constructing the array of objects on the backend Express-side, I stringified each of the objects inside of the array. 在后端Express端构造对象数组时,我将数组内的每个对象进行了字符串化。 Then, I passed the array of stringified JSON objects to the Jade template, which was consequently able to parse and use the data. 然后,我将字符串化的JSON对象数组传递给Jade模板,因此可以解析和使用数据。

try each d, i in JSON.parse(data[0]) each d, i in JSON.parse(data[0])尝试each d, i in JSON.parse(data[0])

Since you send an array of objects you need to go one level deeper to come to the objects. 由于您发送了一个对象数组,因此您需要更深层次地访问对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM