2013-08-16 57 views
1

我想使用Zabbix JSON API在我們的IT商店中自動化一些監控的東西。 我想使用這裏描述的graph.create方法:https://www.zabbix.com/documentation/2.2/manual/api/reference/graph/create哈希表在陣列....和JSON

我正在與gitems數組掙扎。它必須包含散列表(圖中每個項目一個),每個都有「itemid」和「color」行。

這是我的代碼部分:

#i get a list of itemids in $items 
[email protected]("C04000", "800000", "191970", "3EB489", [...]) 
[email protected]{} 
     [email protected]() #an array of hash tables... 

     $c=0 
     foreach ($itemid in $items.result) { 
      [email protected]{} 
      $graphmember.add("itemid", $itemid) 
      $graphmember.add("color", $colours[$c]) 
      $gitems += $graphmember 
      $c += 1 
     } 
     $params.add("gitems", $gitems) 

     #construct the JSON object 
     $objgraph = (New-Object PSObject | Add-Member -PassThru NoteProperty jsonrpc '2.0' | 
     Add-Member -PassThru NoteProperty method 'graph.create' | 
     Add-Member -PassThru NoteProperty params $params | 
     Add-Member -PassThru NoteProperty auth $session.result | 
     Add-Member -PassThru NoteProperty id '2') | ConvertTo-Json 

     return $objgraph 

,當所謂的回報是:

{ 
    "jsonrpc": "2.0", 
    "method": "graph.create", 
    "params": { 
        "gitems": [ 
            "System.Collections.Hashtable", 
            "System.Collections.Hashtable", 
            "System.Collections.Hashtable", 
            "System.Collections.Hashtable", 
            "System.Collections.Hashtable" 
           ] 
       }, 
    "auth": "dc50acf4c337e5430c00936f998f74da", 
    "id": "2" 
} 

,所以我得到5行,這是基於我所提供的參數正確的號碼,但似乎convertto-json不喜歡我的對象...不知道爲什麼。

我在一個陣列的事情是不知道的哈希表,所以我做了一個測試,它似乎工作:

[email protected]() 
[email protected]{} 
$1.add("itemid","123") 
$i1.add("color","blue") 
$gitems += $i1 
[email protected]{} 
$i2.add("itemid","567") 
$i2.add("color","yellow") 
$gitems += $i2 

$gitems 

Name       Value 
----       ----- 
color       bleu 
itemid       123 
color       yellow 
itemid       567 

感謝想法的人!

+0

似乎類似於[這裏](http://stackoverflow.com/questions/17929494/powershell-v3-convertto -json-與嵌入的散列表) –

回答

2

depth參數指定包含的對象在JSON表示中包含的級別。默認值是2。如果你指定值3,JSON將成功創建:

$objgraph = (New-Object PSObject | Add-Member -PassThru NoteProperty jsonrpc '2.0' | 
Add-Member -PassThru NoteProperty method 'graph.create' | 
Add-Member -PassThru NoteProperty params $params | 
Add-Member -PassThru NoteProperty auth $session.result | 
Add-Member -PassThru NoteProperty id '2') | ConvertTo-Json -depth 3