How to use export-CSV when your json file contains key-VALUES pairs instead of key-value pair?

237 views Asked by At

I am using powershell to try and convert Json to csv. I have the bellow Json file that I would like to convert to CSV. But for some reason when I run my code bellow:

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

I am getting this:

hosts                   ips
System.Object[]          System.Object[]

Here's how the json file looks like:

{
    "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"
    ]
}

I want the result to look like this

enter image description here

Please help. I have looked into this for the past couple of hours. I am not really good with powershell. How to do this?

Thanks

1

There are 1 answers

0
js2010 On BEST ANSWER

Like this? I assume the first host goes with the first ip and so on.

$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"