PowerShell调用JSON的address键报错,求不修改JSON的解决方案
解决PowerShell中ConvertFrom-Json后
address键返回奇怪类型的问题 你遇到的System.Object&, System.Private.CoreLib...这种奇怪输出,核心原因是代码里对JSON数组的引用方式错误了。咱们先看问题出在哪,再改代码:
问题根源
从你给出的JSON结构来看,history.addresses是对象数组,每个数组元素都包含address(地址详情对象)和date两个属性。但你的代码在循环$json.history.addresses时,却一直用$json.history.addresses.address.street这种方式取值——这相当于在整个数组上查找address属性,PowerShell找不到对应属性时,就返回了这个奇怪的绑定引用类型,而非实际的属性值。
修复后的代码
只需要修改循环内的取值逻辑,用当前循环项$item来访问对应的address和date即可:
$encoding = [System.Text.Encoding]::UTF8 $i = 0 $ig = 0 $output = @() $Importfile = "Path\file.jsonl" $Exportfile = "Path\file.csv" #If file exists, it will be removed if (test-path $Exportfile) { Remove-Item -path $Exportfile } foreach ($line in [System.IO.File]::ReadLines($Importfile, $encoding)) { $json = $line | ConvertFrom-Json $index = 1 foreach ($item in $json.history.addresses) { $CSVLine = "" | Select-Object Addressstreet, Addresspostalcode, Addresscity, Addressstate, Addresscountry, Addresslat, Addresslng, AddressformattedValue, Datum # 重点修改:用$item.address访问当前循环项的地址属性 $CSVLine.Addressstreet = $item.address.street $CSVLine.Addresspostalcode = $item.address.postalcode $CSVLine.Addresscity = $item.address.city $CSVLine.Addressstate = $item.address.state $CSVLine.Addresscountry = $item.address.country $CSVLine.Addresslat = $item.address.lat $CSVLine.Addresslng = $item.address.lng $CSVLine.AddressformattedValue = $item.address.formattedValue # 同样,用$item.date获取当前项的日期 $CSVLine.Datum = $item.date $output += $CSVLine $index++ } $i++ $ig++ if ($i -ge 20) { $output | Export-Csv -Path $Exportfile -NoTypeInformation -Delimiter ";" -Encoding UTF8 -Append $i = 0 $output = @() Write-Output $ig } if ($ig -ge 120){ break } } $output | Export-Csv -Path $Exportfile -NoTypeInformation -Delimiter ";" -Encoding UTF8 -Append Write-Output $ig
额外优化说明
原来代码里的Select-Object -First $index | Select-Object -Last 1完全没必要,因为$item已经是当前循环的单个地址项,直接访问属性就能拿到对应的值,不需要再做数组筛选操作——这也是之前代码逻辑混乱的一部分原因。
这样修改后,不需要改动任何JSON内容,就能正确获取address下的所有属性值,不会再出现奇怪的类型输出了。
内容的提问来源于stack exchange,提问作者user13320254
相关产品推荐
相关产品推荐

