来自 CSV 的多个 JSON 文件

问题描述 投票:0回答:1

我有一个脚本可以读取 csv 文件的每一行并将所有内容添加到 PsCustomObject 中。它可以创建一个名为 “Kevin Jessica.json” 的 json 文件,其中包含所有值。

{
    "MyClass":  [
                    {
                        "Name":  "Kevin",
                        "Language":  "Powershell",
                        "State":  "Texas"
                    }
                ]
}
{
    "MyClass":  [
                    {
                        "Name":  "Jessica",
                        "Language":  "C",
                        "State":  "NewYork"
                    }
                ]
}

但是,我想为每个人创建一个单独的 json 文件。

whatever3.csv:

Name,Language,State
Kevin,Powershell,Texas
Jessica,C,NewYork

我现在的剧本:

$csvData   = Import-Csv -Path "C:\Users\user1\Downloads\whatever3.csv"
$fileNames = $csvData.Name | Select -Unique
$DestinationDir = "C:\Users\user1\Downloads\sample"
$customheader = "MyClass"

$all = $csvData | ForEach-Object {
    $val = $_ | Select-Object *
[PsCustomObject]@{
$customheader = @($val)
} | ConvertTo-Json | Add-Content -Path "$DestinationDir\$fileNames.json"
}

期望的输出:

凯文.json

{
    "MyClass":  [
        {
            "Name":  "Kevin",
            "Language":  "Powershell",
            "State":  "Texas"
        }
    ]
}

杰西卡.json

{
    "MyClass":  [
        {
            "Name":  "Jessica",
            "Language":  "C",
            "State":  "NewYork"
        }
    ]
}
json powershell
1个回答
0
投票

Add-Content
更改为
Set-Content
并使用每个对象的
.Name
属性的值来创建目标路径:

Import-Csv path\tocsv.csv | ForEach-Object {
    $path = Join-Path $DestinationDir -ChildPath ($_.Name + '.json')
    @{ $customheader = @($_) } | ConvertTo-Json | Set-Content $path
}
© www.soinside.com 2019 - 2024. All rights reserved.