簡體   English   中英

在PowerShell中從csv創建特定的JSON文件

[英]Create a Specific JSON file from csv in PowerShell

我沒有使用PowerShell的經驗,因此我被要求創建此腳本來吸引我的一個朋友。 該腳本應該讀取一個csv文件(這些文件在time和host以外的其他列中是不同的,這在所有文件中都是相同的),然后將其內容輸出到以下格式的JSON文件中:

CSV文件包含以下列:

主機| 留言| 時間| 嚴重性 來源|

{
"time": 1437522387,
"host": "dataserver992.example.com",
"event": { 
    "message": "Something happened",
    "severity": "INFO",
    "source": "testapp"
    #...All columns except for time and host should be under "event"
    }
}

*唯一保證的列是時間和主持人。 所有其他列標題因文件而異。

這是我到目前為止的一部分:

$csvFile = Import-Csv $filePath


function jsonConverter($file)
{    
    #Currently not in use
    $eventString = $file| select * -ExcludeProperty time, host 


    $file | Foreach-Object {
        Write-Host '{'
        Write-Host '"host":"'$_.host'",'
        Write-Host '"time":"'$_.time'",'

        Write-Host '"event":{'

        #TODO: Put all other columns (key, values) under event - Except for 
        time and host

        Write-Host '}'
    }    
}

jsonConverter($csvFile)

關於如何僅逐行提取其余列,將其內容輸出為鍵,值JSON格式(如上例)的任何想法? 謝謝!

只要您的csv看起來像這樣:

"host","message","time","severity","source"
"dataserver992.example.com","Something happened","1437522387","INFO","testapp"

這個腳本:

$filepath = '.\input.csv'
$csvData = Import-Csv $filePath

$NewCsvData  = foreach($Row in $csvData){
   [PSCustomObject]@{
       time  =  $Row.time
       host  =  $Row.host
       event = ($Row| Select-Object -Property * -ExcludeProperty time,host)
   }
}

$NewCsvData | ConvertTo-Json

將輸出此Json:

{
    "time":  "1437522387",
    "host":  "dataserver992.example.com",
    "event":  {
                  "message":  "Something happened",
                  "severity":  "INFO",
                  "source":  "testapp"
              }
}

如果您的Powershell版本是3.0或更高(應該):

Import-CSV $filepath | ConvertTo-JSON

完成!

暫無
暫無

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

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