Javascript 解析 JSON 数组 nodejs
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8449659/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Parsing JSON array nodejs
提问by Alex B
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":
所以我正在学习 NodeJS 和 javascript,并尝试使用它,但在解析 JSON 时遇到了一些问题。我从“用户”收到以下信息:
{
"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).
我一直在尝试通过做 var jsonObject = JSON.parse(req.body); 来做到这一点。,但我不断收到解析错误,无论我如何改变我收到的 JSON(单个组件,所有这些,等等)。
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:
编辑:所以我使用 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);
And then I have index.js, where I basically have the following for each route.
然后我有 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");
}
The request is made with a line free JSON:
请求是用一行免费的 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:
编辑:我意识到我应该将内容类型更改为 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)
采纳答案by Tadeck
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 jsfiddlefor a proof):
如果是(或者您将按照您需要的方式解析它),那么特定的“位”将像这样可用(请参阅此 jsfiddle以获取证明):
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.
在循环中,在迭代jsonObject['sync_contact_list'][i]
之间,“位”之间i
发生变化,因为变化并指向第一个元素,然后指向第二个元素,依此类推,直到最后一个元素。
回答by Alex B
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.
所以事实证明我的 JSON 格式错误。我在 Java 项目上工作时养成的坏习惯。一旦该部分被修复,我的请求就会被默认解析,这引起了其他一些头痛,直到我发现节点检查器。
As a result, I'm selecting Tadeck as having the right answer.
因此,我选择 Tadeck 作为正确答案。
回答by Hemant Tripathi
for(count in sync_contact_list) {
console.log('individual json objects list', JSON.stringify(sync_contact_list[count]));
}