>我在将json转换为对象数组时遇到了奇怪的问题
$response = Invoke-WebRequest -Method Get -UseDefaultCredentials -Uri $url;
$result = ConvertFrom-Json -InputObject $response
write-host $result
它返回空集合(value=System.Object[]
(,尽管json充满了内容。
您能否告知此问题的可能原因和解决方案?
附言。当 URL 包含特定密钥并且仅对 GetAll 情况有问题时,它工作正常。
($input |转换自-JSON( |选择对象
此解决方案对我有用
通常 -inputobject 只能处理 1 个项目。 它更像是管道的占位符。 如果$response是一个数组,你必须这样做,所以convertfrom-json的进程块可以处理所有项目。
$result = $response | ConvertFrom-Json
在您的示例中,唯一的问题是 write-host 似乎将对象数组输出为 null,这似乎是一个错误或"次优行为"。
$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
但是写入输出或简单的$result工作正常:
$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