Javascript 如何获取请求后JSON,然后使用Node.js更改JSON格式?
我有一个JSON格式的传入Post请求,如下所示:Javascript 如何获取请求后JSON,然后使用Node.js更改JSON格式?,javascript,node.js,Javascript,Node.js,我有一个JSON格式的传入Post请求,如下所示: [{"username":"ali","hair_color":"brown","height":1.2},{"username":"marc","hair_color":"blue","height":1.4},{"username":"zehua","hair_color":"black","height":1.8}] 我想将其更改为这种格式,然后将其发送到RESTFUL API: {"h":["username","hair_color
[{"username":"ali","hair_color":"brown","height":1.2},{"username":"marc","hair_color":"blue","height":1.4},{"username":"zehua","hair_color":"black","height":1.8}]
我想将其更改为这种格式,然后将其发送到RESTFUL API:
{"h":["username","hair_color","height"],"d":[["ali","brown",1.2],["marc","blue",1.4],["zehua","black",1.8]]}
问题是如何在不考虑不同参数名称的情况下更改JSON格式,“h
”表示参数名称,“d
”表示值
下面是我的js代码:
var express = require("express");
var myParser = require("body-parser");
var app = express();
app.use(myParser.urlencoded({extended : true}));
app.use(myParser.json());
app.post("/parseJSON", function(request, response) {
console.log(request.body); //This prints the JSON document received (if it is a JSON document)
if(request.body.constructor === Object && Object.keys(request.body).length === 0)
{
response.end("-1");
}
else
{
response.end("0");
}
});
app.get("/parseJSON", function(request, response) {
console.log(request.body); //This prints the JSON document received (if it is a JSON document)
if(request.body.constructor === Object && Object.keys(request.body).length === 0)
{
response.end("-1");
}
else
{
response.end("0");
}
});
app.listen(8080);
你能试试吗
var key = Object.keys(request.body[0])
var data = request.body.map(ele => {
return Object.values(ele);
})
var result = {h:key,d:data};
或
你好!已经编辑了我的问题。请检查一下,并请给我一个关于这个问题的答案@Ankh
const h = Object.keys(request.body[0])
const d = request.body.map(ele => Object.values(ele)) // Use ES7 to enable using Object.values()
const result = {h, d};