0

我目前正在研究在 PowerShell 中调用 ReST 请求的用例。POST 请求的主体是动态创建的,从 CSV 文件中读取数据。

这是我的最终请求正文应该是这样的

{
            "@type": "mtTaskParameter",
            "name": "$src_sfdc$",
            "type": "EXTENDED_SOURCE",
            "sourceConnectionId":"00002E0B00000000000C"
        },
        {
            "@type": "mtTaskParameter",
            "name": "$tgt_db_del$",
            "type": "TARGET",
            "targetConnectionId":"00002E0B00000000000D"
        },
        {
            "@type": "mtTaskParameter",
            "name": "$tgt_db_ups$",
            "type": "TARGET",
            "targetConnectionId":"00002E0B00000000000D"
        },
        {
            "@type": "mtTaskParameter",
            "name": "$tgt_status$",
            "type": "TARGET",
            "targetConnectionId":"00002E0B00000000000D"
        }
}

目前我已经实现如下

if($connectionParameterized -eq "true"){

        $str = @"
        "@type": "mtTaskParameter",
        "name": "$name",
        "type": "$type"
"@

        if($type -eq "SOURCE"){

        $sourceConnectionId = <get source id>

        $str = $str+
        @"
            ,"sourceConnectionId":"$sourceConnectionId"
"@
        }

        if($type -eq "TARGET"){

        $targetConnectionId = <get target id>

        $str = $str+
        @"
        ,"targetConnectionId":"$targetConnectionId"
"@
        }
$finalstr = $finalstr+@"
     {
     $str
     },
"@
}

这很好用,但是代码变得非常混乱并且难以扩展。同样在打印时,格式不正确。

有没有更好的方法来处理这个?

注意:从示例中可以看出,请求正文包含几个特殊字符,如 @、$ 等。

4

1 回答 1

1

如果您包含 CSV,这会更容易,但基本上,您可以将 CSV 作为对象数组导入,然后将其转换为 JSON。

您可以通过添加自定义成员来自定义通过导入 CSV 创建的对象,以便转换为 JSON 为您提供所需的输出。

您还可以对对象数组进行分组或过滤,以根据特定条件制作不同的对象。

这是一些示例代码,可能无法直接使用,但应该在一定程度上展示了该概念:

$json = Import-Csv -Path C:\my\data.csv |
    ForEach-Object -Process {
        $row = $_
        $propName = $row.Type.ToLower() + 'ConnectionId'
        $row | Add-Member -NotePropertyName $propName -NotePropertyValue $out["$mapping_name"].$name -Force -PassThru
    } |
    ConvertTo-Json
于 2016-03-16T14:32:34.987 回答