PowerShell:为JSON嵌套属性赋值数组时格式异常问题排查
PowerShell更新JSON嵌套数组后属性变为字符串格式的解决方法
尝试更新JSON中的嵌套数组属性,执行了读取JSON、转换字符串数组为对象列表、赋值嵌套属性、重新写入JSON这些步骤,但最终JSON文件中目标数组以字符串格式呈现,使用PSObject也没解决问题。相关代码如下:
#REPLACEMENT VALUE LOGIC $possibleOutboundIpAddresses = az functionapp show --name xxx --resource-group yyy --output json --query possibleOutboundIpAddresses $x=$possibleOutboundIpAddresses.Replace('"','') #array of string with IPs $y=$x.Split(',') $array = [System.Collections.Generic.List[object]]::new() $y.ForEach({$array.Add(@{addressRange=$_+"-"+$_})}) #this is the array format I need to replace with $finalInputArray= $array | ConvertTo-Json -Depth 8 $jsonObject=Get-Content C:\Users\input.json | ConvertFrom-Json $jsonObject.p1.p2.p3=$finalInputArray #Output $jsonObject|ConvertTo-Json -Depth 5 |set-content 'C:\Users\RTH163\output.json'
问题原因
核心问题在$finalInputArray= $array | ConvertTo-Json -Depth 8这一步:你已经把IP转换为了对象数组$array,却额外将它转成了JSON字符串。之后把这个字符串赋值给$jsonObject.p1.p2.p3,导致最终再次执行ConvertTo-Json时,该属性被识别为字符串而非数组对象。
解决方法
直接将对象数组$array赋值给目标属性,无需提前转JSON。ConvertFrom-Json生成的$jsonObject是PowerShell对象,直接赋值对象数组后,最后统一转JSON就能生成正确的数组格式:
#REPLACEMENT VALUE LOGIC $possibleOutboundIpAddresses = az functionapp show --name xxx --resource-group yyy --output json --query possibleOutboundIpAddresses $x=$possibleOutboundIpAddresses.Replace('"','') #array of string with IPs $y=$x.Split(',') $array = [System.Collections.Generic.List[object]]::new() $y.ForEach({$array.Add(@{addressRange=$_+"-"+$_})}) # 直接使用对象数组赋值,跳过提前转JSON的步骤 $jsonObject=Get-Content C:\Users\input.json | ConvertFrom-Json $jsonObject.p1.p2.p3=$array #Output $jsonObject|ConvertTo-Json -Depth 5 | Set-Content 'C:\Users\RTH163\output.json'
内容的提问来源于stack exchange,提问作者Dragonknot
相关产品推荐
相关产品推荐

