Parse Array of JSON objects in NodeJS

后端 未结 3 746
自闭症患者
自闭症患者 2020-12-09 12:50

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 JavaScri

相关标签:
3条回答
  • 2020-12-09 12:54

    I'll try to explain this. First of all, you are crating a json string on the client.

    JSON.stringify(QuestionsArray)
    

    Then on the server, you are doing the same again:

    JSON.stringify(req.toString()) // this is not needed
    

    Then you parse the double stringifyed json string to a javascript object:

    JSON.parse(JSON.stringify(req.toString()))
    

    So now you actually have to parse it twice :). If you just stringify it on the server as you are now, and just call:

    var arr = JSON.parse(req.toString());
    

    You will get a javascript object that you can access like this:

    res.end(arr[0].QuestionText.toString());
    

    Have a look at this jsFiddle and open your developer tools. Look at the console when it runs and you will see where the problem is: example

    0 讨论(0)
  • 2020-12-09 13:12

    You may actually send the JSON directly to server.

        $.ajax({
            url: "/echo",
            type: 'POST',
            data: JSON.stringify(QuestionsArray),
            processData: false,
            contentType: 'application/json'
        }).success(function (data) {
            alert(data);
        });
    

    And in node.js, use bodyParser.json to get it back.

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

    By the way, do not use Array as variable name because Array represent the Array class used by JavaScript and your code has overwritten it.

    0 讨论(0)
  • 2020-12-09 13:13

    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);
    });
    
    0 讨论(0)
提交回复
热议问题