Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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": "[email protected]"
    },
    {
      "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':'[email protected]'},{'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)
share|improve this question
1  
What does the parsing error say? You do have to parse the complete response and then just access result.sync_contact_list[0] for the first result. –  Daff Dec 9 '11 at 17:54
1  
Try it with a linebreak-/spacefree json. Does that work? –  Aron Woost Dec 9 '11 at 18:02
 
@AronWoost may be right. Is the data from the user exactly in the format you provided? Or you just formatted it for the StackOverflow? I assumed you are showing us only the structure of the data you want to receive, but we should be given the exact req.body value along with its type (try invoking typeof req.body and give us the result). –  Tadeck Dec 9 '11 at 18:13
1  
@user652360: You're using invalid JSON. –  RightSaidFred Dec 9 '11 at 20:35
2  
...you need double quotes around property names and strings. '{"sync_contact_list":[{"name":"c","number":"789","email":""},{"name":"b","numb‌​er":"123","email":"[email protected]"},{"name":"a","number":"416","email":""}]}' –  RightSaidFred Dec 9 '11 at 20:38
show 3 more comments

2 Answers

up vote 4 down vote accepted

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.

share|improve this answer
add comment

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.

share|improve this answer
3  
What was the bad formatting ? –  guiomie Mar 14 '12 at 2:25
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.