解析NodeJS中的JSON对象数组 [英] Parse Array of JSON objects in NodeJS

查看:1650
本文介绍了解析NodeJS中的JSON对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何解析NodeJS中的JSON对象数组?

I am wondering how can I parse Array of JSON objects in NodeJS?

我想将JSON数组发布到服务器,并能够将接收到的数组用作可靠的JavaScript数组.

I want to post JSON array to the server, and be able to use the received array as a regualar JavaScript array.

谢谢.

这是我的前端部分,我正在使用stringify函数将Array转换为String

This is my front-end part that I am converting Array to String using stringify function

document.getElementById("sendJson").addEventListener("click", function () {
    $.post("/echo", JSON.stringify(QuestionsArray), function (data) {
        alert(data);
    });
})

这是我试图将JSON对象的Array转换为Array的后端部分

This my back-end part that I am trying to convert Array of JSON object to Array

app.post('/echo', function (req, res) {
    var Array = JSON.parse(JSON.stringify(req.toString()));
    res.end(Array[0]["QuestionText"].toString());
});

这是我要发送到服务器的数组:

This is Array that I am trying to sent to the server:

[  
   {  
      "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"
      ]
   }
]

这是源代码

推荐答案

在您的app.js中:

var bodyParser = require("body-parser");
...
app.use(bodyParser.urlencoded({extended: true}));

然后您就可以使用req.body来获取发布的值:

Then you can just use req.body to get the posted values:

app.post('/echo', function (req, res) {
    var Array = req.body.data;
    res.end(Array[0]["QuestionText"].toString());
});

在前端,不要做任何字符串化处理:

In front-end, don't do any stringifying:

$.post("/echo", {data: QuestionsArray}, function (data) {
    alert(data);
});

这篇关于解析NodeJS中的JSON对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆