簡體   English   中英

在Node.js中訪問Json Object上的字段

[英]Accessing field on Json Object in Node.js

所以我是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/');

如您所見,我正在嘗試訪問value字段並嘗試檢索數字5。顯然,它不起作用。 我試圖用谷歌搜索,這可能真的很愚蠢。 關於如何訪問該領域的任何建議?

編輯:

來自console.log(body)的數據:

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(數據):

<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] } ] }

由於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訪問該值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM