【问题标题】:How to use export-CSV when your json file contains key-VALUES pairs instead of key-value pair?当您的 json 文件包含键值对而不是键值对时,如何使用 export-CSV?
【发布时间】:2023-03-29 18:55:01
【问题描述】:

我正在使用 powershell 尝试将 Json 转换为 csv。我有想要转换为 CSV 的波纹管 Json 文件。但是由于某种原因,当我在下面运行我的代码时:

(Get-Content $pathToJsonFile -Raw | ConvertFrom-Json) | Select * | export-CSV $pathToOutputFile -NoTypeInformation 

我得到了这个:

json 文件如下所示:

{
    "hosts": [
        "myserver01",
        "myserver02",
        "myserver03",
        "myserver04",
        "myserver05"
    ],
    "ips": [
        "10.100.0.10",
        "10.111.11.111",
        "10.122.2.22",
        "100.22.111.111",
        "10.111.222.333"
    ]
}

我希望结果看起来像这样

请帮忙。在过去的几个小时里,我已经对此进行了调查。我不太擅长powershell。如何做到这一点?

谢谢

【问题讨论】:

  • 您的 JSON 文件中有两个不相关的数组。您想如何将正确的主机与相应的 IP 连接起来? ...仅仅因为他们的订单?

标签: powershell export-csv convertfrom-json


【解决方案1】:

像这样?我假设第一个主机使用第一个 ip,依此类推。

$a = cat file.json | convertfrom-json

0..($a.hosts.count-1) | 
foreach { [pscustomobject]@{hosts = $a.hosts[$_]; ips = $a.ips[$_]} } | 
convertto-csv


"hosts","ips"
"myserver01","10.100.0.10"
"myserver02","10.111.11.111"
"myserver03","10.122.2.22"
"myserver04","100.22.111.111"
"myserver05","10.111.222.333"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-14
    • 2019-10-19
    • 1970-01-01
    • 1970-01-01
    • 2016-01-17
    • 2018-10-06
    • 1970-01-01
    • 2012-12-25
    相关资源
    最近更新 更多