【问题标题】: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
    
      ...
    

    【讨论】:

      猜你喜欢
      • 2020-10-24
      • 2014-12-14
      • 1970-01-01
      • 1970-01-01
      • 2018-08-01
      • 2015-07-09
      • 2013-05-03
      • 2017-12-18
      • 1970-01-01
      相关资源
      最近更新 更多