0

I've got a JSON like this

[  
   {  
      "Param1":true,
      "Param2":0,
      "Param3":"OK"
      ...
      ...
   }
]

How can I get Param2 value, using powershell 5.1? For now, I tried to get property names, but only get length

$jsondeconverted = $jsonOrig | ConvertFrom-Json
$jsonOrig .PsObject.Properties |
     Select-Object -ExpandProperty Name |
     ForEach-Object {
        Write-Host "Key : " $_
        Write-Host "Value : " $thisJSON."$_"
     }

EDIT This is how I get my json

$jsonvar = '['+$jsonvar+']'
$convertedJson =  $jsonvar | ConvertTo-Json -Depth 10
$deconvertedJson = $convertedJson | ConvertFrom-Json

$deconvertedJson contains only length parameter and nothing more.

1 Answers1

4

You need to look into the object ($jsondeconverted) rather than the string ($jsonOrig)

Based on your json Structure, you would access param2 in the following way $jsondeconverted[0].Param2

Verifiable complete example

$jsonorig = '[{"Param1":true,"Param2":0,"Param3":"OK"}]'
$jsondeconverted = $jsonorig | ConvertFrom-Json
$jsondeconverted[0].param2
Sage Pourpre
  • 9,932
  • 3
  • 27
  • 39
  • I tried this and $jsondeconverted.Param2. These methods returned nothing. – Вася Пупкин Jan 08 '19 at 11:35
  • @ВасяПупкин Then your problem is somewhere else I would think. Can you try the verifiable complete example I added ? – Sage Pourpre Jan 08 '19 at 11:41
  • @Вася Пупкин: Your json is an array. You need to index it like @Sage Pourpre does. `$jsondeconverted.Param2`will not work. – Palle Due Jan 08 '19 at 12:04
  • @PalleDue `$jsondeconverted.param2` also work and is equivalent to : `$jsondeconverted | Select -ExpandProperty param2`. In the simple object above, results would be identical using array index or not. Not using index could result in more than one values in a more complex object though. – Sage Pourpre Jan 08 '19 at 12:41
  • @SagePourpre pls, see my edit. Verifable example works, but I can't make it work through code populated variable – Вася Пупкин Jan 08 '19 at 13:05
  • @ВасяПупкин Check `$convertedJson` structure. Is it really what you show in your example ? Can you debug (F8) `$jsondeconverted` and look at the object ? You should see the structure there. Also, if you are building your json from code, rather than doing that, converting it to json forth and back, you should use a `[PSCustomObject]@{'HashtableKey'='Value}` to generate your PSObject directly. You can later on convert it to json if you need it in that way but you will save yourself the need to escape. – Sage Pourpre Jan 08 '19 at 13:22