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 ponents, 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 IningMessage.<anonymous> (/home/alex/peekcode/quipmail/synch/node_modules/express/node_modules/connect/lib/middleware/bodyParser.js:71:15)
at IningMessage.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)
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 ponents, 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 IningMessage.<anonymous> (/home/alex/peekcode/quipmail/synch/node_modules/express/node_modules/connect/lib/middleware/bodyParser.js:71:15)
at IningMessage.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
edited Dec 9, 2011 at 20:37
Alex B
asked Dec 9, 2011 at 17:53
Alex BAlex B
1,5755 gold badges16 silver badges19 bronze badges
8
- 1 What does the parsing error say? You do have to parse the plete response and then just access result.sync_contact_list[0] for the first result. – Daff Commented Dec 9, 2011 at 17:54
- 1 Try it with a linebreak-/spacefree json. Does that work? – Aron Woost Commented Dec 9, 2011 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 invokingtypeof req.body
and give us the result). – Tadeck Commented Dec 9, 2011 at 18:13 - 1 @user652360: You're using invalid JSON. – RightSaidFred Commented Dec 9, 2011 at 20:35
-
2
...you need double quotes around property names and strings.
'{"sync_contact_list":[{"name":"c","number":"789","email":""},{"name":"b","number":"123","email":"[email protected]"},{"name":"a","number":"416","email":""}]}'
– RightSaidFred Commented Dec 9, 2011 at 20:38
3 Answers
Reset to default 6Maybe 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.
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.
for(count in sync_contact_list) {
console.log('individual json objects list', JSON.stringify(sync_contact_list[count]));
}