gpt4 book ai didi

json - 无法迭代 Node 、express 应用程序中的 json 对象

转载 作者:太空宇宙 更新时间:2023-11-04 03:07:26 25 4
gpt4 key购买 nike

这是我的 Jade 码

block content
.container
#{data} //prints the whole json doc
p Here the list of topics will be shown
for topic,index in data
p #{index}#{topic.title}

此处将显示主题列表”后显示一直到 1002 的连续索引。但没有显示索引旁边的任何数据。

这是我的 json 数据,由 #{data} 打印

[{"_id":"56cc8af53ce0def08a1fa4fa","title":"Rotational Motion","subtopics":[{"stitle":"Introduction","versions":[{"desc":"What is rotational motion?"},{"desc":"Describe it?"}]},{"stitle":"Defination","versions":[{"desc":"Define rotational motion"},{"desc":"Define Rotational motion in detail"}]},{"stitle":"Derivation","versions":[{"desc":"Define rotational motion"},{"desc":"Define Rotational motion in detail"}]}]},{"_id":"56cc71107bb2a0733aba0007","title":"Wave Motion","subtopics":[{"stitle":"Introduction","versions":[{"desc":"What is rotational motion?"},{"desc":"Describe it?"}]},{"stitle":"Defination","versions":[{"desc":"Define rotational motion"},{"desc":"Define Rotational motion in detail"}]}]},{"_id":"56c635b38aff62a82b245e20","title":"Sound and Light","subtopics":[{"stitle":"Introduction","versions":[{"desc":"What is rotational motion?"},{"desc":"Describe it?"}]},{"stitle":"Defination","versions":[{"desc":"Define rotational motion"},{"desc":"Define Rotational motion in detail"}]}]}]

这就是我渲染文件的方式 -

router.get('/', function (req, res) {
var options = {
host: 'someurl',
port: 80,
path: '/topics'
};

http.get(options, function(webresponse) {
console.log("Got response: " + webresponse.statusCode);

webresponse.on("data", function(chunk) {
console.log("data: " + chunk);
var data = chunk;
console.log(data); //prints the json data correctly
//rendering html with params
res.render('index', { user : req.user , data : data });

});
}).on('error', function(e) {
console.log("Got error: " + e.message);
});
});

最佳答案

Jade 使用 each 而不是 for。将您的代码更新为数据中的每个主题,它应该可以正常工作。

Jade Docs

编辑:根据您的服务器代码,data 似乎只是一个以字符串形式返回的 JSON 对象,这就是您无法正确循环它的原因。在将 JSON.parse(data) 发送到渲染器之前使用 JSON.parse(data) 应该可以解决该问题

关于json - 无法迭代 Node 、express 应用程序中的 json 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35797961/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com