簡體   English   中英

如何從初始JSON輸出中獲取“p”的值

[英]how to get value of “p” from the initial JSON output

我從服務器端獲得連續的JSON輸出。

{"first":"XXXABC1","second":{"t":35,"p":800}}

{"first":"XXXXABC2","second":{"t":35,"p":1000}}

{"first":"XXXXABC2","second":{"t":35,"p":1000}}

我想使用800處的開始JSON數據或顯示的任何數字來記錄和修復p的值。 有什么辦法嗎? 對不起之前的混亂

我可以在底部添加此代碼嗎?

   document.getElementById("p2").innerHTML = message.second.p[0];
...
 function doSend()
  {

    var jsonGetData = {"command": 1, "second":["p","t"]};
    var jsonGetDataAll = {"command": 2};                                    

    {
      console.log("SENT: " + JSON.stringify(jsonGetData));
      websocket.send(JSON.stringify(jsonGetData));
    }
}

function onMessage(evt)
  {
    var message = JSON.parse(evt.data);

    console.log('>RESPONSE: ' +evt.data);
    document.getElementById("t").innerHTML = message.second.t;
    document.getElementById("p").innerHTML = message.second.p;
  }

這很簡單,請嘗試以下方法:

//For JSON Object from server
var jsonObject = {
    "first": "XXXABC1",
    "second": {
        "t": 35,
        "p": 800
    }
};
let expected_value = '';
if (jsonObject.second.p != null && jsonObject.second.p != undefined && isFinite(jsonObject.second.p)) {
    expected_value = jsonObject.second.p;
}
console.log(expected_value);


//For JSON Array from server
var jsonArray = [
    {
        "first": "XXXABC1",
        "second": {
            "t": 35,
            "p": 800
        }
    },
    {
        "first": "XXXXABC2",
        "second": {
            "t": 35,
            "p": 1000
        }
    },
    {
        "first": "XXXXABC2",
        "second": {
            "t": 35,
            "p": 1200
        }
    },
];
let expected_value = '';
if (jsonArray.length > 0) {
    let jsonObject = jsonArray[0];
    if (jsonObject.second.p != null && jsonObject.second.p != undefined && isFinite(jsonObject.second.p)) {
        expected_value = jsonObject.second.p;
    }
}
console.log(expected_value);

如果我理解正確,你想獲得JSON數組的第一項,那么使用數組索引:

function onMessage(evt)
{
    var message = JSON.parse(evt.data);

    console.log('>RESPONSE: ' +evt.data);
    if(evt.data.length && evt.data.length > 0){
        document.getElementById("t").innerHTML = message[0].t;
        document.getElementById("p").innerHTML = message[0].p;
    }        
}

暫無
暫無

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

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