简体   繁体   中英

Convert JSON array to single JSON object in Powershell

I am trying to convert JSON array into single JSON Object. Below is the output screenshot在此处输入图片说明

I want the output as在此处输入图片说明

I am using the below powershell script

$getdb_Conn=Invoke-Sqlcmd -ServerInstance $ServerName -Database 'master' -Username $UserName -Password $Password -Query $getdb
$deadlockDB=$getdb_Conn.Database_Name
$deadlockSP=$getdb_Conn.SP_Name
$deadlockTable_Name=$getdb_Conn.Table_Name
$deadlockTIMESTAMP=$getdb_Conn.TIMESTAMP

$Obj = [PSCustomObject]@{
    Database = $deadlockDB
    SP = $deadlockSP
    Table = $deadlockTable_Name
    TIMESTAMP = $deadlockTIMESTAMP
    }

    Write-Output ( $obj | ConvertTo-Json) 

Please someone help me, on how to the get required output. I do not want the JSON in an array.

The issue is you have one single non-array object that contains properties, which all contain arrays of values. To achieve the desired results, you need an array of objects that each contain one set of property values. You can choose to do this at the source when you are building $Obj or build a new set of objects to be sent to ConvertTo-Json .

For building a new set of objects using your current $Obj :

for ($i = 0; $i -lt $obj.TIMESTAMP.Count; $i++) {
    [pscustomobject]@{
        Database = $obj.Database[$i]
        SP = $obj.SP[$i]
        Table = $obj.Table[$i]
        TIMESTAMP = $obj.TIMESTAMP[$i]
    } | ConvertTo-Json
}

Building the objects from the source data:

$getdb_Conn=Invoke-Sqlcmd -ServerInstance $ServerName -Database 'master' -Username $UserName -Password $Password -Query $getdb    
foreach ($conn in $getdb_Conn) {
    [PSCustomObject]@{
        Database = $conn.Database_Name
        SP = $conn.SP_Name
        Table = $conn.Table_Name
        TIMESTAMP = $conn.TIMESTAMP
    } | ConvertTo-Json
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM