Why does ConvertTo-Json drop values

2019-07-23 11:33发布

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.

1条回答
SAY GOODBYE
2楼-- · 2019-07-23 11:59

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
查看更多
登录 后发表回答