9

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

5
  • If you are already sending a stringified array (why would you do that in the first place), why do you stringify it on the server again? Commented Feb 24, 2015 at 22:45
  • Without stringify in NodeJS part I get exception. s1.postimg.org/v2urhx0kf/Capture.png Commented Feb 24, 2015 at 22:46
  • You need to use bodyparser middleware and just post the array without stringifying. Commented Feb 24, 2015 at 22:50
  • @VsevolodGoloviznin Please Help man, I am stuck for days on this. Commented Feb 24, 2015 at 22:54
  • req.body could work, and remove over complexities of parsing and stringifying Commented Feb 24, 2015 at 23:00

3 Answers 3

10

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);
});
Sign up to request clarification or add additional context in comments.

1 Comment

thankyou so much. I suspected it had something to do with the bodyParser. But wouldn't have found it in a week
4

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

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.