PowerShell - 遍历 JSON

PowerShell - Iterate through JSON

我看过很多示例,但我的代码无法正常工作。这个 JSON 的结构似乎与我见过的任何其他结构都不一样。我需要遍历这些结果并获得“id”和“legalName”。

[
    "URL: https://myurl.com/rest/api",
    {
        "value":  [
                      {
                          "id":  271,
                          "client":  "@{id=245; clientCode=; clientName=}",
                          "dbaName":  null,
                          "federalEIN":  "",
                          "legalCode":  "01",
                          "legalName":  "Test1",
                          "naicsCode":  null,
                          "status":  "Active",
                          "links":  "    "
                      },
                      {
                          "id":  272,
                          "client":  "@{id=245; clientCode=; clientName=}",
                          "dbaName":  null,
                          "federalEIN":  "",
                          "legalCode":  "02",
                          "legalName":  "Test2",
                          "naicsCode":  null,
                          "status":  "Terminated",
                          "links":  "    "
                      }
                  ],
        "Count":  6
    }
]

我已经尝试了很多不同的代码示例,但其中 none 行得通。这个returns没什么。我似乎无法深入了解我需要的属性。

$var = Get-RestData("https://myurl.com/rest/api/") | ConvertTo-Json
$var["value"] | select id

您可以使用 ConvertFrom-Json cmdlet 将 JSON 格式的字符串转换为可以迭代的 PSCustomObject

$json = @"
[
    "URL: https://myurl.com/rest/api",
    {
        "value":  [
                      {
                          "id":  271,
                          "client":  "@{id=245; clientCode=; clientName=}",
                          "dbaName":  null,
                          "federalEIN":  "",
                          "legalCode":  "01",
                          "legalName":  "Test1",
                          "naicsCode":  null,
                          "status":  "Active",
                          "links":  "    "
                      },
                      {
                          "id":  272,
                          "client":  "@{id=245; clientCode=; clientName=}",
                          "dbaName":  null,
                          "federalEIN":  "",
                          "legalCode":  "02",
                          "legalName":  "Test2",
                          "naicsCode":  null,
                          "status":  "Terminated",
                          "links":  "    "
                      }
                  ],
        "Count":  6
    }
]
"@
$json | ConvertFrom-Json | ForEach-Object { $_.value } | Select id, legalName

哪个returns:

 id legalName
 -- ---------
271 Test1
272 Test2