【发布时间】:2020-09-04 02:30:24
【问题描述】:
我正在从目录中读取一些 json 文件并将它们用作端点。我有以下代码:
fs.readdir(dirPath, function (err, filesPath) {
if (err) throw err;
filesPath = filesPath.map(function(filePath){
return dirPath + filePath;
});
async.map(filesPath, function(filePath, cb){
fs.readFile(filePath, 'utf8', cb);
}, function(err, results) {
res.send(results);
});
});
这会返回如下内容:
[
{
"Country1":{
"countryTEST":"US",
"FindLocale":{
"Test":{
"Test":false,
"Test":""
},
"Test":{
"Test":false,
"Test":"value"
}
},
"payment":[
"CREDIT_CARD",
"NOT_CREDIT"
],
"test":"1234",
"phoneNumb":[
""
]
},
"Country2":{
"countryTEST":"US",
"FindLocale":{
"Test":{
"Test":false,
"Test":""
},
"Test":{
"Test":false,
"Test":"value"
}
},
"payment":[
"CREDIT_CARD",
"NOT_CREDIT"
],
"test":"1234"
"phoneNumb":[
""
]
}
}
]
但是,我希望返回的响应看起来像这样(没有包装对象的数组)
{
"Country1":{
"countryTEST":"US",
"FindLocale":{
"Test":{
"Test":false,
"Test":""
},
"Test":{
"Test":false,
"Test":"value"
}
},
"payment":[
"CREDIT_CARD",
"NOT_CREDIT"
],
"test":"1234"
"phoneNumb":[
""
]
},
"Country2":{
"countryTEST":"US",
"FindLocale":{
"Test":{
"Test":false,
"Test":""
},
"Test":{
"Test":false,
"Test":"value"
}
},
"payment":[
"CREDIT_CARD",
"NOT_CREDIT"
],
"test":"1234"
"phoneNumb":[
""
]
}
}
我尝试过类似 res.send(JSON.stringify(results)); 和 res.send(JSON.parse(results)); 的操作。但这并没有让我得到我想要的输出。
请建议我如何获得所需的输出。欢迎任何建议。谢谢!
【问题讨论】:
-
res.send(results[0]);适合你吗? -
@RahulBhobe 我试过 res.send(results[0]);但它只会返回第一个对象,例如 country1,但我希望返回所有对象 country1....country200
-
看看这个answer是否适合你。我假设您的输入就是您所说的输入。但在您的原始帖子中,它们似乎有所不同。
-
从数组中获取第一个元素
arr[0] -
@RahulBhobe 如果我提供的示例太简单,我感到非常抱歉。您的代码肯定通过了我提供的示例。然而,我的 JSON 实际上看起来更像这样(我已经编辑了描述)
标签: javascript node.js arrays json parsing