![](/img/trans.png)
[英]In D3 Sankey, how can I load the from objects or arrays instead of either json or csv files?
[英]How can I return objects instead of objects inside an array when reading from json files?
我正在从目录中读取一些 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.stringify(results));
和res.send(JSON.parse(results));
. 但这并没有让我得到我想要的输出。
请建议我如何获得我需要的输出。 欢迎任何建议。 谢谢!
将数组转换为对象:
let arr = [ { "country1": { "capital": "some capital", "currency": "$" } }, { "country2": { "capital": "some capital", "currency": "$" } } ]; let obj = Object.assign({}, ...arr); console.log(obj);
请试试这个您需要该数组的第一个元素并进行解析。
res.send(JSON.parse(results[0]));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.