我想知道如何解析NodeJS中的
JSON对象数组?
我想将JSON数组发布到服务器,并能够将接收到的数组用作regualar JavaScript数组.
提前致谢.
这是我使用stringify函数将Array转换为String的前端部分
document.getElementById("sendJson").addEventListener("click",function () {
$.post("/echo",JSON.stringify(QuestionsArray),function (data) {
alert(data);
});
})
这是我的后端部分,我试图将JSON对象的数组转换为数组
app.post('/echo',function (req,res) {
var Array = JSON.parse(JSON.stringify(req.toString()));
res.end(Array[0]["QuestionText"].toString());
});
这是我试图发送到服务器的数组:
[
{
"QuestionText":"What is your Name","QuestionType":1
},{
"QuestionText":"Where are you from","QuestionType":2,"ChoiceList":[
"US","UK"
]
},{
"QuestionText":"Are you married","QuestionType":3,"ChoiceList":[
"Yes","No"
]
}
]
Here is the source code
解决方法
在你的app.js中:
var bodyParser = require("body-parser");
...
app.use(bodyParser.urlencoded({extended: true}));
然后你可以使用req.body来获取发布的值:
app.post('/echo',res) {
var Array = req.body.data;
res.end(Array[0]["QuestionText"].toString());
});
在前端,不要做任何字符串化:
$.post("/echo",{data: QuestionsArray},function (data) {
alert(data);
});