首页 > 解决方案 > 来自 Azure DevOps Api 的 Powershell Json 数组内容

问题描述

    {
"count":  3,
"value":  [
              {
                  "id":  "12345678-123456-23424-123456ff2",
                  "name":  "TestProject",
                  "description":  "Test project  migration",
                  "url":  "https://dev.azure.com",
                  "state":  "wellFormed",
                  "revision":  6619,
                  "visibility":  "private",
                  "lastUpdateTime":  "2019-10-14T06:10:03.557Z"
              },
              {
                  "id":  "12345678-123456-23424-123456ff2",
                  "name":  "KC-TestAutomation-Framework",
                  "description":  "Test Automation Frameworks",
                  "url":  "https://dev.azure.com",
                  "state":  "wellFormed",
                  "revision":  6502,
                  "visibility":  "private",
                  "lastUpdateTime":  "2019-10-03T07:53:33.95Z"
              },
              {
                  "id":  "b2345678-123456-23424-12345",
                  "name":  "Training",
                  "description":  "Training Management Project",
                  "url":  "https://dev.azure.com",
                  "state":  "wellFormed",
                  "revision":  7124,
                  "visibility":  "private",
                  "lastUpdateTime":  "2019-12-02T07:19:24Z"
              }
     ]
}

我有这个 Json,我需要从这个 json 创建另一个 json,其中包含每个项目的名称和 ID,格式为 name:name value:id in json file...

我试过这样的东西..

   $json = Get-Content $file | ConvertFrom-Json 

   ForEach($i in $json.value.id)
    {
      Write-Host "Id: $($i)","name: $($json.value.name)"
    }

标签: arraysjsonpowershell

解决方案


  • 读取 JSON 文件并使用ConvertFrom-Json.
  • 选择 id 和 name 属性并转换回 json
  • 将新创建的 json 写入文件

像这样的东西:

$json = Get-Content -Path 'X:\YourJsonFile.json' | ConvertFrom-Json

$newJson = $json.value | Select-Object id, name | ConvertTo-Json

# output on screen
$newJson

# output to new json file
$newJson | Set-Content -Path 'X:\YourNewJsonFile.json'

输出:

[
    {
        "id":  "12345678-123456-23424-123456ff2",
        "name":  "TestProject"
    },
    {
        "id":  "12345678-123456-23424-123456ff2",
        "name":  "KC-TestAutomation-Framework"
    },
    {
        "id":  "b2345678-123456-23424-12345",
        "name":  "Training"
    }
]

推荐阅读