JS獲取Json值以及通過值獲取索引


我的JSON格式是這樣(大概截取一段展示下):

"result":{
        "total":179,
        "list":[
            {
                "id":"b8:27:eb:8d:dd:c8",
                "hostname":"2l3f-wt-board",
                "osversion":"3.5.1",
                "osbuild":"14009",
                "resolution":"1360x768",
                "ip":"10.99.105.156",
                "monitor":"SHARP_HDMI",
                "lastupdate":1533607224293,
                "append":{
                    "lostheartbeat":false,
                    "cputemperature":61.2
                }
            },
            {
                "id":"b8:27:eb:c4:d7:6c",
                "hostname":"D-Office",
                "osversion":"3.5.1",
                "osbuild":"14009",
                "resolution":"1360x768",
                "ip":"10.99.67.141",
                "monitor":"5000_Series",
                "lastupdate":1533607215300,
                "append":{
                    "lostheartbeat":false,
                    "cputemperature":52.6
                }
            },
            {
                "id":"b8:27:eb:97:a9:5a",
                "hostname":"SCC-Andon",
                "osversion":"3.5.1",
                "osbuild":"14009",
                "resolution":"1920x1080",
                "ip":"169.254.88.215",
                "monitor":"Mi_TV",
                "lastupdate":1533607214146,
                "append":{
                    "lostheartbeat":false,
                    "cputemperature":41.9
                }
            },
    ]
}

 首先我們來獲取對應的值,比如獲取ip:

//將JSON轉化下
        data = $.parseJSON(TextBox1.value);
        //遍歷json
        for (i in data) {
            var list = data[i].list
            for (a in list) {
               list[a].ip
            }
        }

  

反之如果我知道ip多少,如何查找該ip對應的其他key的值呢?

思路:

1,我們可以將ip先一次性全部從json中拿出來且轉換成數組:

        //將JSON轉化下
        data = $.parseJSON(TextBox1.value);
        //遍歷json
        for (i in data) {
            var list = data[i].list
            var AllIp;
            for (a in list) {
                AllIp += list[a].ip + ",";
            }
            var IPArry = AllIp.split(",");
        }

2,如上代碼IPArry 即獲取到所有ip,現在就好辦了,知道ip,就很容易獲取器索引了:

var result = IPArry.indexOf(‘iP’);

3,獲取到索引,那就很容易獲取到該ip對應的其他key的值了

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM