2016-07-30 60 views
1

我有以下JSON一個SNMP設備的創建一個可讀的輸出:如何從SNMP設備遍歷對象,並使用預定義規則

mib = [ 
    "1.3.6.1.2.1.43.11.1": { 
     "1.1": { 
      "3": "1", 
      "5": "3", 
      "6": "Cyan Toner Cartridge, WorkCentre 6505N", 
      "8": "2000", 
      "9": "800" 
     }, 
     "1.2": { 
      "3": "2", 
      "5": "3", 
      "6": "Magenta Toner Cartridge, WorkCentre 6505N", 
      "8": "1000", 
      "9": "400" 
     }, 
     "1.5": { 
      "3": "0", 
      "5": "9", 
      "6": "Imaging Unit, WorkCentre 6505N", 
      "8": "24000", 
      "9": "24000" 
     } 
    }, 
    "1.3.6.1.2.1.43.12.1": { 
     "1.1": { 
      "4": "cyan" 
     }, 
     "1.2": { 
      "4": "magenta" 
     } 
    } 
] 

結果我想出來的是這樣的:

device["markerSupplies"]: [ 
    0: { 
     color: "cyan", 
     type: "toner", 
     description: "Cyan Toner Cartridge, WorkCentre 6505N", 
     capacity: "2000", 
     value: "800" 
    }, 
    1: { 
     color: "magenta", 
     type: "toner", 
     description: "Magenta Toner Cartridge, WorkCentre 6505N", 
     capacity: "1000", 
     value: "400" 
    }, 
    2: { 
     color: "", 
     type: "opc", 
     description: "Imaging Unit, WorkCentre 6505N", 
     capacity: "24000", 
     value: "24000" 
    }, 
] 

「1.1」,「1.2」...只是索引我有關於它們內部的內容的信息。 它們內部的每個屬性都稱爲一列,並與其索引對應。

我知道有關每個表列如下:

1.3.6.1.2.1.43.11.1 
    3 the color index inside 1.3.6.1.2.1.43.12.1 
    5 
     3 "toner" 
     9 "opc" 
    6 description 
    8 capacity 
    9 level 

1.3.6.1.2.1.43.12.1 
    4 color name 

如何可以創建一個JSON信息對象,使用JavaScript代碼我可以在JSON從裝置 迭代和創建輸出結果我上面顯示?

+0

如何可靠是關鍵,像'1.3.6.1.2.1.43.11.1'? –

+0

使用打印機mib我知道1.3.6.1.2.1.43.11.1是prtMarkerSuppliesTable –

回答

1

您可以使用顏色和類型的一些幫助變量,並遍歷鍵來構建新的數組。

var mib = { "1.3.6.1.2.1.43.11.1": { "1.1": { 3: "1", 5: "3", 6: "Cyan Toner Cartridge, WorkCentre 6505N", 8: "2000", 9: "800" }, "1.2": { 3: "2", 5: "3", 6: "Magenta Toner Cartridge, WorkCentre 6505N", 8: "1000", 9: "400" }, "1.5": { 3: "0", 5: "9", 6: "Imaging Unit, WorkCentre 6505N", 8: "24000", 9: "24000" } }, "1.3.6.1.2.1.43.12.1": { "1.1": { 4: "cyan" }, "1.2": { 4: "magenta" } } }, 
 
    cols = { 3: 'color', 5: 'type', 6: 'description', 8: 'capacity', 9: 'level' }, 
 
    types = { 3: 'toner', 9: 'opc' }, 
 
    markerSupplies = mib['1.3.6.1.2.1.43.11.1'], 
 
    colors = mib['1.3.6.1.2.1.43.12.1'], 
 
    result = Object.keys(markerSupplies).map(function (k) { 
 
     var o = {}; 
 
     Object.keys(cols).forEach(function (c) { 
 
      if (c === '3') { 
 
       o[cols[c]] = (colors[k] || {})['4'] || ''; 
 
       return; 
 
      } 
 
      if (c === '5') { 
 
       o[cols[c]] = types[markerSupplies[k][c]] || ''; 
 
       return; 
 
      } 
 
      o[cols[c]] = markerSupplies[k][c] || ''; 
 

 
     }); 
 
     return o; 
 
    }); 
 

 
console.log(result);

+0

嗨妮娜!我對這個答案有很大的瞭解,現在我有一個類似的問題,需要解決一些問題,我希望你能提供幫助。 http://stackoverflow.com/questions/38790637/how-to-iterate-over-an-object-and-create-an-output-using-some-rules-i-define –