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

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

问题描述

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

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

提前致谢.

这是我使用字符串化函数将数组转换为字符串的前端部分

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

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

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

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

<预><代码>[{"QuestionText":"你叫什么名字",问题类型":1},{"QuestionText":"你来自哪里","问题类型":2,选择列表":[我们",英国"]},{"QuestionText":"你结婚了吗","问题类型":3,选择列表":[是的",不"]}]

这是源代码

解决方案

在你的 app.js 中:

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

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

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

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

$.post("/echo", {data: QuestionsArray}, function (data) {警报(数据);});

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

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

Thanks in advance.

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);
    });
})

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

Here is the source code

解决方案

In your app.js:

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

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天全站免登陆