【问题标题】:Accessing JSON values in an express web server在快速 Web 服务器中访问 JSON 值
【发布时间】:2012-04-18 17:41:56
【问题描述】:
我能够使用this answer 中的代码访问发布到服务器的 JSON 字符串中的值。
如果服务器获得{"MyKey":"My Value"},则可以使用request.body.MyKey 访问"MyKey" 的值。
但发送到我的服务器的 JSON 字符串如下所示:
[{"id":"1","name":"Aaa"},{"id":"2","name":"Bbb"}]
我找不到访问其中任何内容的方法。你是怎么做到的?
【问题讨论】:
标签:
json
web-services
parsing
node.js
express
【解决方案1】:
request.body 是一个标准的 JavaScript 对象,在你的例子中是一个普通的 JavaScript 数组。您只需像处理任何 JavaScript Array 对象一样处理 request.body。例如
app.post('/', function(request, response){
var users = request.body;
console.log(users.length); // the length of the array
var firstUser = users[0]; // access first element in array
console.log(firstUser.name); // log the name
users.forEach(function(item) { console.log(item) }); // iterate the array logging each item
...