【问题标题】:Create a Specific JSON file from csv in PowerShell在 PowerShell 中从 csv 创建特定的 JSON 文件
【发布时间】:2019-05-31 04:18:38
【问题描述】:

我没有使用 PowerShell 的经验,我被要求创建这个脚本以帮助我的一个朋友。该脚本应该读取一个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 格式(如上面的示例)的任何想法? 谢谢!

【问题讨论】:

    标签: json powershell csv


    【解决方案1】:

    如果您的 powershell 版本是 3.0 或更高版本(应该):

    Import-CSV $filepath | ConvertTo-JSON
    

    完成!

    【讨论】:

    • 嘿,这不起作用,因为“事件”实际上不是 csv 文件中的列。 “事件”就像一个键,我必须在其中放置除主机和时间之外的所有列。这是一个自定义的 JSON 文件。见上面的例子。
    • 刚刚烘焙了类似@LotPings 的东西。但略逊一筹。所以使用他的代码;-)
    【解决方案2】:

    如果您的 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"
                  }
    }
    

    【讨论】:

    • 我一开始不记得参数-ExcludeProperty需要参数-Property也存在。
    • 很好的解决方案!非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2017-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-02
    • 2021-12-24
    相关资源
    最近更新 更多