我有一个Node.js API,它返回如下格式的JSON:
[
{
"id" : "1",
"tstamp": "2017-06-01T00:00:00.000Z",
"dmemberprofiles","48400"
"dgroupprofiles","4800"
"msclprofiles","400"
},
{
"id" : "2",
"tstamp" : "2017-06-02T00:00:00.000Z",
"dmemberprofiles","48700"
"dgroupprofiles","4900"
"msclprofiles","410
}
]
如何让Node.js返回JSON,如下所示:
{
"header": [
"id",
"tstamp",
"dmemberprofiles",
"dgroupprofiles",
"msclprofiles"
],
"data": [
{
"id" : "1",
"tstamp" : "2017-06-01T00:00:00.000Z",
"dmemberprofiles","48400"
"dgroupprofiles","4800"
"msclprofiles","400"
},
{
"id" : "2",
"tstamp" : "2017-06-02T00:00:00.000Z",
"dmemberprofiles","48700"
"dgroupprofiles","4900"
"msclprofiles","410
}
]
}
我已经四处寻找其他示例,但尚未找到Node.js特定的解决方案。
答案 0 :(得分:1)
您可以使用Object.keys
从数组的第一个对象获取键。
var array = [{ id: "1", tstamp: "2017-06-01T00:00:00.000Z", dmemberprofiles: 48400, dgroupprofiles: 4800, msclprofiles: 400 }, { id: "2", tstamp: "2017-06-02T00:00:00.000Z", dmemberprofiles: 48700, dgroupprofiles: 4900, msclprofiles: 410 }],
object = { header: Object.keys(array[0]), data: array };
console.log(object);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 1 :(得分:0)
假设
var data = [
{
"id" : "1",
"tstamp": "2017-06-01T00:00:00.000Z",
"dmemberprofiles","48400"
"dgroupprofiles","4800"
"msclprofiles","400"
},
{
"id" : "2",
"tstamp" : "2017-06-02T00:00:00.000Z",
"dmemberprofiles","48700"
"dgroupprofiles","4900"
"msclprofiles","410
}
]
然后就这样做:
// Add data to wrapper
var wrapper = {
"header": [
"id",
"tstamp",
"dmemberprofiles",
"dgroupprofiles",
"msclprofiles"
],
"data": data
}
// Convert to JSON
var json = JSON.stringify( wrapper );