Read multiple values from Json file in Poweshell

Viewed 74

I want to Read Multiple values from Json file

My Json file Looks like this

{
  "TestEvent": ["TVIA_Gold","TVIA_Silver"],
  "Folder": ["DealerPortal","VehiclePortal"],
  "NEL": [3,1]
}

Output should be like:

TVIA_Gold 
DealerPortal
3

TVIA_Silver 
VehiclePortal
1

Or

TestEvent      Folder         NEl
TVIA_GOLD      DealerPortal    3
TVIA_SILVER    VehiclePortal   1

My code is below:

$file= Get-Content "C:\Test.json"   
$file2=$file
$file=$file2 | ConvertFrom-Json
$vPSObject= $file2 | ConvertFrom-Json 
$vPSObject.TestEvent
$vPSObject.Folder
$vPSObject.NEL


Output : 
TVIA_Gold
TVIA_Silver
DealerPortal
VehiclePortal
3
1

...but it doesn't work. Should I use array and loop with it?

1 Answers

Your JSON data seems invalid for output you expect. Instead it should be something like this then:

[
  {
    "TestEvent": "TVIA_GOLD",
    "Folder": "DealerPortal",
    "NEl": "3"
  },
  {
    "TestEvent": "TVIA_SILVER",
    "Folder": "VehiclePortal",
    "NEl": "1"
  }
]

If you insist to use your JSON input data as shown by you you may assume there is a relation between the elements of the actually unrelated single arrays in your JSON data. Then you could use something like this:

$ImportData = Get-Content -Path C:\test.json | ConvertFrom-Json

for ($i = 0; $i -lt $ImportData.testevent.Count; $i++) {
    [PSCustomObject]@{
        TestEvent = $ImportData.TestEvent[$i]
        Folder    = $ImportData.Folder[$i]
        NEL       = $ImportData.NEL[$i]
    }
}
Related