json - 在 PowerShell 中从 csv 创建特定的 JSON 文件

标签 json powershell csv

我没有使用 PowerShell 的经验,我被要求创建这个脚本作为我的一个 friend 的恩惠。该脚本应该读取 csv 文件(这些文件除了时间和主机之外具有不同的列,这些列在所有文件中都是通用的),并将其内容输出到以下格式的 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"
              }
}

关于json - 在 PowerShell 中从 csv 创建特定的 JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54041551/

相关文章:

从快捷方式更改桌面的 Powershell 脚本

python + CSV : Sum up Similar Values from a CSV columns

java - 无法使用 Apache Commons CSV 读取 CSV 文件 - IllegalArgumentException

C# JsonConvert - 具有多种类型的列表列表

javascript - 将 JavaScript 数组作为 JSON 值发送?

windows - 在特定 CPU 负载下运行程序的脚本

sql - ASP 更新数据库,如果不存在则插入

ios - Swift 中的 JSON 复杂数组

python - LUIS.ai json 迁移到 Rasa 格式 json 不返回实体,但返回正确的意图

powershell - 能否将 CmdletBinding 与未绑定(bind)参数结合使用?