2016-08-23 124 views
0

說明 嵌套數組和對象不正確地轉換爲JSON


使用ConvertTo-Json Powershell的,我想下面的對象轉換:

$richmessage = @{ 
    attachments = @(
     @{ 
      "mrkdwn_in" = @("text"; "pretext";); 
      "title" = "title here"; 
      "title_link" = "http://somelinkhere/"; 
      "fallback" = "Summary of the attachment"; 
      "text" = "message"; 
      "color" = "red";  

     })  
} 

write-host(ConvertTo-Json -InputObject $richmessage) 

我希望得到這個輸出:

{ 
    "attachments": [ 
        { 
         "text": "message", 
         "fallback": "Summary of the attachment", 
         "mrkdwn_in": ["text" "pretext"], 
         "color": "red", 
         "title": "title here", 
         "title_link": "http://somelinkhere/" 
        } 
       ] 
} 

但實際輸出是:

{ 
    "attachments": [ 
        { 
         "text": "message", 
         "fallback": "Summary of the attachment", 
         "mrkdwn_in": "text pretext", 
         "color": "red", 
         "title": "title here", 
         "title_link": "http://somelinkhere/" 
        } 
       ] 
} 

注意


  • 我想"mrkdwn_in": "text pretext"mrkdwn_in:["text", "pretext"]
  • 如果我們把$richmessage = @{ "mrkdwn_in" = @("text"; "pretext"); }這將產生數組不如預期,但是當陣列嵌套像這樣:$richmessage = @{ attachments = @(@{"mrkdwn_in" = @("text"; "pretext"); }) } ;它會對字符串進行分解。
  • 我正在使用此功能發佈一條豐富的消息至Slack,並允許在附件中標記。 (見this link

問題


我怎樣才能做到這一點?

回答

0

嘗試增加數組值對象分別

$richmessage= $richmessage["attachments"][0]["mrkdwn_in"] = @("text", "pretext"); 

完整的示例:

$richmessage = @{ 
    attachments = @(
     @{ 
      "mrkdwn_in" = ""; 
      "title" = "title here"; 
      "title_link" = "http://somelinkhere/"; 
      "fallback" = "Summary of the attachment"; 
      "text" = "message"; 
      "color" = "red";  

     })  
} 
+0

已經嘗試過,仍然給我相同的結果:' 「mrkdwn_in」: 「文本由頭」'。 –

+0

我已更正我的答案。 – SergeDirect

+0

謝謝,我看到了,但這是一個語法錯誤(我在Windows PowerShell ISE上運行它)。請記住,這是Powershell腳本,不是JavaScript或任何其他腳本語言。 –