解析JSON数组Node.js

6

我正在学习NodeJS和javascript,尝试使用它并遇到了一些解析JSON的问题。我从“用户”那里收到以下内容:

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

我的问题是如何正确解析这个数据以获取单独的位:

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

我一直在尝试通过 var jsonObject = JSON.parse(req.body); 来实现,但无论我如何变化接收到的JSON(单独组件、全部等),都会出现解析错误。
有人能指出我哪里做错了吗?
编辑: 所以我使用express来处理不同的路径。所以我有一个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);

然后我有一个index.js,对于每个路由大致如下。

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");
}

请求使用一行无空格的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

编辑:我意识到应该将内容类型更改为application/json。在这种情况下,对于JSON.stringify,我得到以下结果:

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
解析错误提示了什么?您需要解析完整的响应,然后只需访问result.sync_contact_list [0]以获取第一个结果。 - Daff
1
尝试使用无换行/空格的JSON格式。这样可以吗? - Aron Woost
@AronWoost可能是对的。用户提供的数据是否完全符合您提供的格式?还是您只是为了在StackOverflow上格式化它?我假设您只是向我们展示要接收的数据结构,但是我们应该提供精确的req.body值以及其类型(尝试调用typeof req.body并给出结果)。 - Tadeck
1
@user652360:您正在使用无效的JSON。 - RightSaidFred
2
你需要在属性名称和字符串周围使用双引号。'{"sync_contact_list":[{"name":"c","number":"789","email":""},{"name":"b","number":"123","email":"a@a.com"},{"name":"a","number":"416","email":""}]}' - RightSaidFred
显示剩余3条评论
3个回答

6
也许它已经被解析了?我不知道(我没有看到你的全部代码)。
如果是这样(或者您将按照需要解析它),那么特定的“位”将可用,如此(请参见此jsfiddle以获取证明):
for (var i=0; i<jsonObject['sync_contact_list'].length; i++){
    // here jsonObject['sync_contact_list'][i] is your current "bit"
}

循环中,迭代过程中,jsonObject['sync_contact_list'][i]在“位”之间变化,因为i的值会改变,指向第一个元素,然后是第二个元素,以此类推,直到最后一个元素。


2
所以事实证明我的JSON格式不正确,这是我从Java项目中获得的不良习惯。一旦修复了这部分,我的请求被默认地解析,这导致了其他一些问题,直到我发现node-inspector为止。
因此,我选择Tadeck作为正确答案。

0
for(count in sync_contact_list) {
           console.log('individual json objects list', JSON.stringify(sync_contact_list[count]));
}

3
虽然这段代码可能回答了问题,但提供关于它为什么或如何回答问题的额外背景信息可以提高其长期价值。 - jay.sf

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接