0

I have faced with strange issue in time of conversion of json to the objects array

$response = Invoke-WebRequest -Method Get -UseDefaultCredentials  -Uri $url;
$result = ConvertFrom-Json -InputObject $response
write-host $result

It returns empty collection (value=System.Object[]) despite the json is full of content.

Could you please advise possible cause and solution of this issue?

PS. It works fine when URL contains specific Key and has issue only for the GetAll case.

js2010
  • 23,033
  • 6
  • 64
  • 66
  • How do you determine that it is an empty collection? The comment "*(value=System.Objext[])*", suggests that you transferring it back to Json, and just face a known issue: [Unexpected ConvertTo-Json results? Answer: it has a default -Depth of 2](https://stackoverflow.com/q/53583677/1701026) – iRon Dec 01 '19 at 17:30

2 Answers2

0

Usually -inputobject can only process 1 item. It's more of a placeholder for piping. If $response is an array, you'll have to do it this way, so convertfrom-json's process block can process all the items.

$result = $response | ConvertFrom-Json

In your example, the only problem is write-host seems to output the object array as null, which seems like a bug or "suboptimal behavior".

$response = ' [ {"Type": "1","Name": "First"}, {"Type": "2","Name": "Second"}, {"Type": "3","Name": "Third"} ] '
$result = convertfrom-json -inputobject $response
write-host $result   

(write-host $result) -eq $null

True

But write-output or simply $result works ok:

$response = ' [ {"Type": "1","Name": "First"}, {"Type": "2","Name": "Second"}, {"Type": "3","Name": "Third"} ] '
$result = convertfrom-json -inputobject $response
$result

Type Name
---- ----
1    First
2    Second
3    Third


js2010
  • 23,033
  • 6
  • 64
  • 66
  • Thank you for the idea. It good point that the ConvertFrom-Json can porocess only one object, at least by default. I checked it with example. But looks like $result = $response | ConvertFrom-Json returns the same result System.Object[]. Has it any parameter or workaround ? – Andreas Petrov Dec 02 '19 at 05:31
  • Definitely, the cause of issue is that ConvertFrom-Json does not convert the arrays by default $input = ' [ {"Type": "1","Name": "First"}, {"Type": "2","Name": "Second"}, {"Type": "3","Name": "Third"} ] ' $output = $input | ConvertFrom-Json Write-Host $output # Nothing $cnt = (convertFrom-Json $input).Count Write-Host $cnt #3 How to make it working with arrays? – Andreas Petrov Dec 02 '19 at 06:17
  • That example isn't really a powershell string array. $input is a reserved variable, so a different name would work better. Yes, it's odd that write-host seems to output nothing. It seems to try to convert it to a string. $output by itself would work fine, or write-output $output. – js2010 Dec 02 '19 at 07:06
0

($input | ConvertFrom-Json) | Select-Object

This solution works for me