PowerShell解析REST API返回JSON时path值输出异常,求代码修正方案
问题:PowerShell解析Azure DevOps REST API返回的JSON数组获取文件路径出错
我通过REST API获取到包含多个item的ChangesInfoJson数组,需要遍历item下的path值。返回的JSON结构如下:
[ { "item": { "objectId": "dd6d17aa11bexxxx110aeedb", "originalObjectId": "98a11c2fe8xxxx33a089fc62e986", "gitObjectType": "blob", "commitId": "a73b19232650xxxx1b6d4a6c969", "path": "/pipeline/PL_xxxx_START.json", "url": "https://dev.azure.com/xxxx" }, "changeType": "edit" }, { "item": { "objectId": "13e6685cdxxxx485968d9e159", "originalObjectId": "48d0cf8xxxx19a43064", "gitObjectType": "blob", "commitId": "a73b19232650fxxx4a6c969", "path": "/trigger/TRIGGER_xxxxx_WKLY.json", "url": "https://dev.azure.com/xxxx" }, "changeType": "edit" } ]
我使用以下PowerShell代码解析:
$ChangesInfoJson | foreach { $_.psobject.properties | foreach { $_.value | foreach { $_.psobject.properties | foreach { if ($_.name -eq "path"){ write-host change file path is:$_.value } } } } }
但输出结果为:
"change file path is: string path=/pipeline/PL_xxxx.json.value"
期望的正确输出是:change file path is: /pipeline/PL_xxxx.json,请问该如何修改代码?
解决方案
你的代码嵌套了过多不必要的psobject.properties遍历,导致访问到错误的属性层级。PowerShell解析JSON后会直接生成结构化对象,你可以直接访问对象属性,无需逐层遍历所有属性。
修改后的代码如下:
$ChangesInfoJson | ForEach-Object { Write-Host "change file path is: $($_.item.path)" }
代码说明
$ChangesInfoJson是已解析的JSON数组,通过ForEach-Object直接遍历数组中的每个元素- 每个元素的
item属性是包含path的子对象,直接通过$_.item.path即可获取目标路径值 - 使用
$()在字符串中嵌入属性值,确保PowerShell正确解析变量并输出预期格式
内容的提问来源于stack exchange,提问作者Joy
相关产品推荐
相关产品推荐

