我需要使用pug迭代json数组。
通过使用此路线
app.get('/drone', function(req, res, next) {
console.log(mqttClient.drone_gps_json)
res.render('drone', {
title: 'drone',
message: (mqttClient.drone_gps_json)
});
})
我有这个输出
[
'{"type": "Point", "coordinates": [5.068762643835973, 4.348367550295752]}',
'{"type": "Point", "coordinates": [5.230064273129623, 4.0352242534817835]}',
'{"type": "Point", "coordinates": [4.724948591970712, 4.93405260010674]}',
'{"type": "Point", "coordinates": [4.177566385080386, 5.875375587957874]}',
...
]
为了可视化json数组,我使用了以下pug文件:
html
head
title= title
body
h1= message
它工作
然而,我想要一个项目符号列表,如:
* "type": "Point", "coordinates": [5.068762643835973, 4.348367550295752]
* "type": "Point", "coordinates": [5.230064273129623, 4.0352242534817835]
* ...
正如这里已经建议的那样,我尝试了:
html
head
title= title
body
ul
each item in message
li= message
但我有一个错误:
GET /drone 500 211.871 ms - 1111
Error: Failed to lookup view "error" in views directory "/webserver/views"
建议?
您可能会遇到问题,因为请求输出是一个字符串列表,看起来像JSON。但它并不像看上去那样是一个对象列表。
您可以使用JSON.parse((将字符串转换为JSON对象。您还可以使用map方法对数组的每个字符串应用JSON.parse。
这里有一个例子:
var resp = [
'{"type": "Point", "coordinates": [5.068762643835973, 4.348367550295752]}',
'{"type": "Point", "coordinates": [5.230064273129623, 4.0352242534817835]}',
'{"type": "Point", "coordinates": [4.724948591970712, 4.93405260010674]}',
'{"type": "Point", "coordinates": [4.177566385080386, 5.875375587957874]}'
] ;
var formattedArr = resp.map( str => JSON.parse(str) );
console.log("list of strings : ",resp);
console.log("list of objects : ", formattedArr);
我不知道那能不能解决你的问题。希望它能有所帮助;(