簡體   English   中英

Powershell 將txt文件的所有行轉換為JSON格式

[英]Powershell to convert all lines of txt file to JSON format

我有 output.txt 文件包含:

device:VM01,partition:"C",size_gb:100
device:VM02,partition:"D",size_gb:200
device:VM03,partition:"E",size_gb:150

在閱讀每一行並使用 ConvertTo-Json 后,我期望得到結果:

[
{
    "device": "VM01",
    "partition": "C",
    "size_gb": 100
},
{
    "device": "VM02",
    "partition": "D",
    "size_gb": 200
},
{
    "device": "VM01",
    "partition": "E",
    "size_gb": 150
}
]

但它返回:

"device:VM01,partition:\"C\",size_gb:100"

更新我的代碼:

$source_file = ".\output.txt"
$text = (Get-Content -Path $source_file -ReadCount 0) -join "`n"
$text | ConvertTo-Json

我怎樣才能用 PowerShell 得到它?

這是一個基於Import-Csv的通用解決方案,它不依賴於硬編碼的列/屬性名稱或列的特定順序。 注意使用內部成員.psobject.Properties通過Import-Csv反映對象 output 的屬性(列)。

請注意,代碼假定您的output.txt CSV 文件確實有 header 行,即使您沒有在示例數據中顯示它。 如果它確實沒有 header 行,請使用-Header a,b,c提供(虛擬)列名。

Import-Csv output.txt | ForEach-Object {
    $oht = [ordered] @{} # Create an aux. (ordered) hashtable.
    # Loop over the column values, split them into name and value,
    # and add them to the aux. hashtable.
    foreach ($prop in $_.psobject.Properties.Value) {
        # Split into name and value, and remove enclosing double quotes.
        $name, $val = $prop.Split(':').Trim('"')
        # If the value can be interpreted as an integer, convert it to one.
        if ($val -as [int]) { $val = [int] $val }
        $oht[$name] = $val  # Add an entry.
    }
    $oht # Output the hashtable for processing by ConvertTo-Json
} | ConvertTo-Json

你可以嘗試這樣的事情:

$FileContent = Get-Content C:\temp\stack.txt
$ArrayOfDevices = @()

Foreach ( $Line in $FileContent)
{

    $CurrentSplit = $Line.split(',')
    $CurrentDevice = $CurrentSplit[0].split(':')[1]
    $CurrentPartition = $CurrentSplit[1].split(':')[1].replace('"','')
    $CurrentSize = [int]$CurrentSplit[2].split(':')[1]

    $ArrayOfDevices +=  [pscustomobject]@{
        "device" = $CurrentDevice
        "Partition" = $CurrentPartition
        "Size_GB" = $CurrentSize
    }
}

$ArrayOfObjects | convertto-json

所以,我得到用逗號分隔符分割的每一行的文件內容,然后創建一個自定義對象。 這個 object 存儲在一個數組中。 在循環之后,我們將數組轉換為 json。

但是,如果您可以將 output.txt 的格式更改為適當的 CSV,這將使您的生活更輕松。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM