2011-12-09 77 views
6

所以我一般在学习NodeJS和javascript,并且玩弄它,我在解析JSON时遇到了一些问题。我收到了从“用户”以下内容:解析JSON数组nodejs

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

我的问题是如何能够正确地解析这个让各个位:做VAR

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

我一直在试图做到这一点jsonObject = JSON.parse(req.body); ,但我不断收到解析错误,无论我如何改变我收到的JSON(单个组件,全部等)。

任何人都可以指出我做错了什么?

编辑: 所以我用快递处理不同的路径。所以,我有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':'[email protected]'},{'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

尝试使用linebreak-/spacefree json。那样有用吗? –

+0

@AronWoost可能是对的。用户提供的数据是否完全**以您提供的格式显示?或者你只是将它格式化为StackOverflow?我假设你只向我们展示了你想要接收的数据的结构,但是我们应该给出确切的'req.body'值及其类型(尝试调用'typeof req.body'并给我们结果)。 – Tadeck

回答

6

也许它已被解析?我不知道(我没有看到你的整个代码)。

如果是(或者你会解析它,你需要的方式),那么具体的“位”将提供类似的(见this 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项目中获得的坏习惯。一旦该部分被修复,我的请求就会被默认解析,这导致了一些其他的头痛,直到我发现了节点检查器。

因此,我选择Tadeck作为正确答案。

+7

错误的格式化是什么? – guiomie