为什么 ConvertTo-Json 丢弃值 [英] Why does ConvertTo-Json drop values

查看:19
本文介绍了为什么 ConvertTo-Json 丢弃值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 powershell 来探索 REST API.我发现了一个奇怪的异常.当我序列化/描述以下对象时,responses 对象消失了!我已经验证在转换为 .net 对象时它仍然完好无损,因此从 .net 对象转换为 JSON 时会出现问题.

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": "  "
    }
  ]
}

如果我运行这个,我会收到 54,正如预期的那样:

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

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

我在 Ubuntu 上运行,但不相信这会有所作为.这对于使用 Windows 的人来说应该很容易验证.

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

推荐答案

ConvertTo-Json 需要一个可选的 Depth 参数(无论出于何种原因)默认为 2.参数本身在链接的文档中描述如下:

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:

指定包含在 JSON 表示中的包含对象的级别数.默认值为 2.

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

如果您为此参数提供更高的值,它将起作用 - 最大值 值为 100:

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

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

这篇关于为什么 ConvertTo-Json 丢弃值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆