嵌套数组和对象未正确转换为json

时间:2016-08-23 20:49:25

标签: json powershell nested slack-api

描述

<小时/> 在 Powershell 中使用ConvertTo-Json,我正在尝试转换以下对象:

$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

问题

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分: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";       

        })      
}