Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing JSON array nodejs

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)
like image 240
Alex B Avatar asked Dec 09 '11 17:12

Alex B


People also ask

How do I parse a JSON array in node JS?

nodejs-parse-json-file.js // include file system module var fs = require('fs'); // read file sample. json file fs. readFile('sample. json', // callback function that is called when reading file is done function(err, data) { // json data var jsonData = data; // parse json var jsonParsed = JSON.

How do you parse an array in JSON?

Use the JSON. parse() method to pase a JSON array, e.g. JSON. parse(arr) . The method parses a JSON string and returns its JavaScript value or object equivalent.

Does JSON parse return an array?

When using the JSON.parse() on a JSON derived from an array, the method will return a JavaScript array, instead of a JavaScript object.


1 Answers

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.

like image 68
Tadeck Avatar answered Nov 03 '22 13:11

Tadeck