使用Powershell从数据库字段创建数组对象,然后将结果转换为json对象

时间:2019-01-17 16:22:53

标签: powershell

我的查询定义如下:

./gradlew launchIOSDevice

$Query = "Select field1, field2, field3 from table 是逗号分隔的字段:field3

我正在使用Powershell的ConvertTo-Json方法将结果返回到Json对象中。所以我的结果看起来像这样:

valueA,valueB,valueC

我要完成的工作是将field3值存储在数组对象中,这样我的愿望结果就是这样:

{
    "field1" : "value1",
    "field2" : "value2",
    "field3" : "valueA,valueB,valueC"
}

使用powershell是否可以完成?

2 个答案:

答案 0 :(得分:0)

'{
"field1" : "value1",
"field2" : "value2",
"field3" : "valueA,valueB,valueC" 
}' | ConvertFrom-JSON | select field1, field2, @{n = 'field3' ;e = {$_.field3 -split ','}} | ConvertTo-Json

您需要这样的东西吗? 结果将是这样的: enter image description here

答案 1 :(得分:-1)

Thank you for your responses. I FINALLY figured it out.  
I hope this can help someone else. Here is my code:

$connectionString = "Server="ServerName"; User ID="UserName";
 password="password"    database="Database"
$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $connection
$connection.Open()
$command = $connection.CreateCommand()
$command.CommandText = "select field1, field2, field3 from table  "
$result = $command.ExecuteReader()

##Create an empty array on the target field and finalResult:
$arrayField3 = @()
$finalResult = @()

while($result.Read())
{
    $Field1 = $result["field1"]
    $Field2 = $result["field2"]
    $Field3 = $result["field3"]
    $Field3Split = $Field3.Split(",")
    foreach($item in $Field3Split)
    {
        $arrayField3 += @($item)
    }
 $finalResult += New-Object psObject -Property @{'Field1'=$Field1; 
'Field2'=$Field2; 'Field3'= $arrayField3}
}
## DON'T FORGET TO ADD A DEPTH
$Json = $finalResult | ConvertTo-Json -Depth 5 

### The results of $Json looks like this:
{
    "Field1" : "Value1",
    "Field2" : "Value2",
    "Field3" : [
                 "ValueA",
                 "ValueB",
                 "ValueC"  
               ]
}
@Victor Dronov: Your solution is better (less code).  
How do you remove the "Count": 3 as one of the field values?