11

Powershell can't seem to correctly round-trip this JSON object:

{
    "settings": {
        "minimumApproverCount": 2,
        "creatorVoteCounts": false,
        "scope": [
            {
                "refName": "refs/heads/d14rel",
                "matchKind": "Exact",
                "repositoryId": "a290117c-5a8a-40f7-bc2c-f14dbe3acf6d"
            }
        ]
    }
}

Assuming $json is a string, this command:

$json | ConvertFrom-Json | ConvertTo-Json

produces the wrong JSON out of it:

{
    "settings":  {
                     "minimumApproverCount":  2,
                     "creatorVoteCounts":  false,
                     "scope":  [
                                   "@{refName=refs/heads/d14rel; matchKind=Exact; repositoryId=a290117c-5a8a-40f7-bc2c-f14db
e3acf6d}"
                               ]
                 }
}

Notice it gets the "scope" variable wrong. Is there a way to fix this?

Andrew Arnott
  • 80,040
  • 26
  • 132
  • 171

1 Answers1

12

Use the parameter Depth with value 3 or larger. The default 2 is not enough, deeper data are simply converted to strings.

$json | ConvertFrom-Json | ConvertTo-Json -Depth 3

Output

{
    "settings":  {
                     "minimumApproverCount":  2,
                     "creatorVoteCounts":  false,
                     "scope":  [
                                   {
                                       "refName":  "refs/heads/d14rel",
                                       "matchKind":  "Exact",
                                       "repositoryId":  "a290117c-5a8a-40f7-bc2c-f14dbe3acf6d"
                                   }
                               ]
                 }
}
Roman Kuzmin
  • 40,627
  • 11
  • 95
  • 117
  • The max depth is 100 as of October 2019 (via [ConvertTo-Json's source code](https://github.com/PowerShell/PowerShell/blob/fe56f9d90238ede0a77c5eb3c7190c2d459cd8be/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertToJsonCommand.cs#L29)). – Eric Eskildsen Oct 15 '19 at 14:58