【问题标题】:Modifying JSON file using data from CSV in PowerShell在 PowerShell 中使用来自 CSV 的数据修改 JSON 文件
【发布时间】:2019-04-29 21:43:04
【问题描述】:

我正在尝试根据 .csv 文件中的两列修改 .json 文件中的某些特定值。如果 .json 文件中的当前值与左列中的值相同,我想将其更改为右列中的值。

这是我第一次使用 PowerShell,所以我正在努力弄清楚如何去做。我觉得我的解决方案不仅是错误的,而且在可能不需要的时候使用了双 for 循环。这是我目前所拥有的。

$jsonData = Get-Content -Path $jsonFile | ConvertFrom-Json
$csvData = Get-Content -Path $csvFile | Select-Object -Skip 1 # Skipping the header

foreach ($jsonItem in $jsonData.'Placeable List') {
    foreach ($csvRow in $csvData) {
        $splitRow = $csvRow -split ","
        $lCol = $splitRow[0]
        $rCol = $splitRow[1]

        $currentItem = $jsonItem.'value'.'Appearance'.'value'
        if ($currentItem -eq $lCol) {
            $currentItem -eq $rCol
        }
    }
}

【问题讨论】:

    标签: json powershell csv


    【解决方案1】:

    我设法弄明白了。

    $csvData  = Get-Content -Path $csvFile | Select-Object -Skip 1 # Skipping the header
    $jsonData = Get-Content -Path $jsonFile -raw | ConvertFrom-Json
    
    foreach($csvRow in $csvData) {
        $splitRow = $csvRow -split ","
        $lCol = $splitRow[0]
        $rCol = $splitRow[1]
    
        foreach($item in $jsonData.'Placeable List'.value) {
            $item.Appearance | % {
                if ($_.value -eq $lCol) {
                    $_.value = $rCol
                }
            }
        }
    }
    
    $jsonData | ConvertTo-Json -depth 32 | Set-Content $jsonFile
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-14
      • 1970-01-01
      • 2018-08-18
      • 1970-01-01
      • 2021-09-30
      • 2017-03-29
      • 2020-09-07
      • 2023-01-11
      相关资源
      最近更新 更多