javascript - 解析 JSON 数组 nodejs
所以我正在学习 NodeJS 和 JavaScript 一般知识,并且在玩它时,我在解析 JSON 时遇到了一些问题。我从“用户”那里收到以下内容:
{
"sync_contact_list": [
{
"name": "c",
"number": "789",
"email": ""
},
{
"name": "b",
"number": "123",
"email": "[email "
},
{
"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':'[email '},{'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
也许它已经被解析了?我不知道(我没有看到你完整的代码)。
如果是这样(或者你将以你需要的方式解析它),那么特定的“位”将像那样可用(参见这个 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] 会在“bits”之间变化,因为 i 会变化,指向第一个元素,然后是第二个元素,依此类推,直到最后一个元素。
答案#2
原来我的 JSON 格式很糟糕。这是我在做 Java 项目时养成的坏习惯。一旦那部分修好了,我的请求就会被默认解析,这引起了一些其他问题,直到我发现了 node-inspector。
因此,我选择 Tadeck 作为有正确答案的人。
