Parsing JSON array nodejs


Question

so I'm learning NodeJS and javascript in general, and playing around with it and I have some problems parsing a JSON. I receive the following from the "user":

{
  "sync_contact_list": [
    {
      "name": "c",
      "number": "789",
      "email": ""
    },
    {
      "name": "b",
      "number": "123",
      "email": "a@a.com"
    },
    {
      "name": "a",
      "number": "416",
      "email": ""
    }
  ]
}

My question is how can i properly parse this to get the individual bits:

{
  "name": "a",
  "number": "416",
  "email": ""
}

I've been trying to do it by doing var jsonObject = JSON.parse(req.body); ,but I keep getting parsing errors, no matter how I vary the JSON that I do receive (individual components, all of it, etc).

Could anyone one point out what I'm doing wrong?

EDIT: So i use express to deal with the different paths. So i have app.js:

var express = require('express')
  , routes = require('./routes')
//var mysql = require('mysql');
var app = module.exports = express.createServer();

// Configuration

app.configure(function(){
  app.set('views', __dirname + '/views');
  //app.set('view engine', 'jade');
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});

app.configure('development', function(){
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); 
});

app.configure('production', function(){
  app.use(express.errorHandler());  
});

// Routes

//app.post('/', routes.syncServiceIndex);

app.post('/syncService', routes.synchServicePost);
app.get('/syncService/:syncServiceUser/sync', routes.synchServiceSync);
app.post('/syncService/:syncServiceUser/push', routes.synchServicePush);
app.del('/syncService/:syncServiceUser', routes.synchServiceDel);

app.post('/syncService/:syncServiceUser/contacts/push', routes.synchServiceContactsPush);
app.get('/syncService/:syncServiceUser/contacts/sync', routes.synchServiceContactsSync);

app.post('/syncService/:syncServiceUser/contacts/', routes.synchServiceContactsPost);
app.get('/syncService/:syncServiceUser/contacts/:contactId', routes.synchServiceContactsGet);
app.put('/syncService/:syncServiceUser/contacts/:contactId', routes.synchServiceContactsPut);
app.del('/syncService/:syncServiceUser/contacts/:contactId', routes.synchServiceContactsDel);


app.listen(3000);


console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);

And then I have index.js, where I basically have the following for each route.

exports.synchServicePost = function(req, res) {
    console.log('synchServicePost');
    console.log("BODY:"+JSON.stringify(req.body));
    var jsonObject = JSON.parse(req.body);


    res.statusCode = 200;
    res.send("OK\n");
}

The request is made with a line free JSON:

curl -i -d "{'sync_contact_list':[{'name':'c','number':'789','email':''},{'name':'b','number':'123','email':'a@a.com'},{'name':'a','number':'416','email':''}]}"  http://localhost:3000/syncService

EDIT: I realized I should probably change the Content Type to application/json. in this case, for JSON.stringify I get the following:

SyntaxError: Unexpected token ILLEGAL
at parse (native)
at IncomingMessage.<anonymous> (/home/alex/peekcode/quipmail/synch/node_modules/express/node_modules/connect/lib/middleware/bodyParser.js:71:15)
at IncomingMessage.emit (events.js:61:17)
at HTTPParser.onMessageComplete (http.js:133:23)
at Socket.ondata (http.js:1029:22)
at Socket._onReadable (net.js:677:27)
at IOWatcher.onReadable [as callback] (net.js:177:10)
1
6
12/9/2011 8:37:16 PM

Accepted Answer

Maybe it is already parsed? I do not know (I did not see your whole code).

If it is (or you will parse it the way you need), then specific "bits" will be available like that (see this jsfiddle for a proof):

for (var i=0; i<jsonObject['sync_contact_list'].length; i++){
    // here jsonObject['sync_contact_list'][i] is your current "bit"
}

Within the loop, between iterations, jsonObject['sync_contact_list'][i] changes between the "bits", because i changes and points to the first element, then to the second, and so on, until the last element.

6
12/9/2011 6:10:52 PM

So it turns out my JSON was badly formatted. Bad habit I got from working on a Java project. Once that part was fixed, my request was getting parsed by default, which caused some other headache until I found out about node-inspector.

As a result, I'm selecting Tadeck as having the right answer.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon