1

I am using powershell to explore a REST API. I discovered a strange anomaly. When I serialize/descrialize the following objct, the responses object are gone! I have verified that it is all still in tact when converted to .net object, so the problem happens when converting from .net object to JSON.

$json  = @'
{
  "stubs": [
    {
      "responses": [
        {
          "is": {
            "body": "54"
          }
        },
        {
          "is": {
            "body": "21"
          }
        },
        {
          "is": {
            "body": "0"
          }
        }
      ]
    }
  ]
}
'@
$json | ConvertFrom-Json | ConvertTo-Json

The result form the above conversion is this:

{
  "stubs": [
    {
      "responses": "  "
    }
  ]
}

If I run this, I receive 54, as expected:

$json | ConvertFrom-Json | %{ $_.stubs.responses[0].is.body }  

I am running on Ubuntu, but don't believe that should make a difference. This should be easy to verify for someone on Windows.

Phillip Scott Givens
  • 5,256
  • 4
  • 32
  • 54
  • 2
    Possible duplicate of [Cannot convert PSCustomObjects within array back to JSON correctly](https://stackoverflow.com/questions/38742767/cannot-convert-pscustomobjects-within-array-back-to-json-correctly) – iRon Nov 17 '18 at 19:35

1 Answers1

7

ConvertTo-Json takes an optional Depth parameter that (for whatever reason) defaults to 2. The parameter itself is described in the linked docs as follows:

Specifies how many levels of contained objects are included in the JSON representation. The default value is 2.

If you provide a higher value for this parameter, it’ll work - The maximum value is 100:

$json | ConvertFrom-Json | ConvertTo-Json -Depth 100
Kirk Larkin
  • 84,915
  • 16
  • 214
  • 203