访问Node.js中Json对象上的字段

时间:2015-06-17 17:02:00

标签: javascript json

所以我是JavaScript编程的新手。我在POST请求中获取此JSON有效负载:

{
  "subscriptionId" : "asdasdasdasd",
  "originator" : "localhost",
  "contextResponses" : [
    {
      "contextElement" : {
        "type" : "",
        "isPattern" : "false",
        "id" : "id",
        "attributes" : [
          {
            "name" : "temperature",
            "type" : "int",
            "value" : "5"
          }
        ]
      },
      "statusCode" : {
        "code" : "200",
        "reasonPhrase" : "OK"
      }
    }
  ]
}

使用此代码尝试访问某个字段:

var qs = require('querystring');
var http = require('http');
http.createServer(function (req, res) {
var obj;

if (req.method == 'POST') {
        var body = '';
        req.on('data', function (data) {
            body += data;
            console.log(body.attributes.value);
            if (body.length > 1e6)
                req.connection.destroy();
        });

        req.on('end', function () {
            var post = qs.parse(body);
            // use post['blah'], etc.
        });
    }
}).listen(8087, "188.???.??.???");
console.log('Server running at http://188.???.??.???:8087/');

正如您所见,我试图访问值字段并尝试检索数字5.显然,它无法正常工作。我试着谷歌它,这可能是非常愚蠢的东西。关于如何访问该领域的任何建议?

修改

来自console.log(正文)的数据:

Server running at http://????????
{
  "subscriptionId" : "asdasdasdasd",
  "originator" : "localhost",
  "contextResponses" : [
    {
      "contextElement" : {
        "type" : "",
        "isPattern" : "false",
        "id" : "fiwaresensorfinal",
        "attributes" : [
          {
            "name" : "temperature",
            "type" : "int",
            "value" : "5"
          }
        ]
      },
      "statusCode" : {
        "code" : "200",
        "reasonPhrase" : "OK"
      }
    }
  ]
}

console.log(data):

<Buffer 7b 0a 20 20 22 73 75 62 73 63 72 69 70 74 69 6f 6e 49 64 22 20 3a 20 22 35 35 38 31 37 62 33 62 39 38 61 64 64 31 38 63 63 33 65 31 38 33 62 65 22 2c 0a ...>

console.log(recv):

{ subscriptionId: '55817b3b98add18cc3e183be',
  originator: 'localhost',
  contextResponses: [ { contextElement: [Object], statusCode: [Object] } ] }

1 个答案:

答案 0 :(得分:1)

由于http模块将data作为字符串返回,因此您需要先将接收到的数据解析为JSON对象:

而不是:

req.on('data', function (data) {
        body += data;
        console.log(body.attributes.value);
        ....
});

这样做:

req.on('data', function (data) {
        var recv = JSON.parse(data);
        console.log(recv.contextResponses[0].contextElement.attributes[0].value);
        ....
});

如果您收到的来自服务器的回复数据与您在第一段中发布的数据相同,那么您可以通过.contextResponses[0].contextElement.attributes[0].value访问该值。