【问题标题】:Powershell ConvertTo-JSON missing nested levelPowershell ConvertTo-JSON 缺少嵌套级别
【发布时间】:2018-02-12 08:13:11
【问题描述】:

如果嵌套太深,Powershell 会在导出到 JSON 时切断数据。我的对象层次结构如下所示:

Main Object
    Metadata
    More Metadata
    Collection of Other object Sources
        Collection of data used by these sources

由于某种原因,当我转换为 JSON 时,powershell 将第三级(这些源使用的数据的集合)导出为一个空字符串,即使它是一个添加了各种 NoteProperties 的对象数组。例如:

$test = New-Object -TypeName PSObject

$obj = New-Object -TypeName PSObject
$obj | Add-Member -MemberType NoteProperty -Name "Name" -Value "adsf"

$test2 = New-Object -TypeName PSObject
$test2 | Add-Member -MemberType NoteProperty -Name "ArrayTest" -Value @($obj, $obj)

$test3 = New-Object -TypeName PSObject
$test3 | Add-Member -MemberType NoteProperty -Name "ArrayTest" -Value @($obj, $obj, $obj)

$test | Add-Member -MemberType NoteProperty -Name "CollectionTest" -Value @($test2, $test3)

这会产生以下 JSON 字符串:

PS C:\Users\user\projects\Powershell> $test | ConvertTo-Json
{
    "CollectionTest":  [
                           {
                               "ArrayTest":  " "
                           },
                           {
                               "ArrayTest":  "  "
                           }
                       ]
}

转换为 XML 会产生类似的情况:

<?xml version="1.0"?>
<Objects>
  <Object Type="System.Management.Automation.PSCustomObject">
    <Property Name="CollectionTest" Type="System.Object[]">
      <Property Type="System.Management.Automation.PSCustomObject">
        <Property Type="System.String">@{ArrayTest=System.Object[]}</Property>
        <Property Name="ArrayTest" Type="System.Management.Automation.PSNoteProperty">System.Object[]</Property>
      </Property>
      <Property Type="System.Management.Automation.PSCustomObject">
        <Property Type="System.String">@{ArrayTest=System.Object[]}</Property>
        <Property Name="ArrayTest" Type="System.Management.Automation.PSNoteProperty">System.Object[]</Property>
      </Property>
    </Property>
  </Object>
</Objects>

powershell 中是否存在某种对象嵌套限制?

【问题讨论】:

    标签: json powershell


    【解决方案1】:

    来自 Get-Help ConvertTo-JSON:

    -深度
    指定 JSON 表示中包含多少级别的包含对象。默认值为 2。

    将 -Depth 参数设置为保存数据所需的任何深度。

    【讨论】:

    • 呃,谢谢!不知道我是如何在帮助中错过的!
    • 也许你错过了它,因为它是一个奇怪的参数。
    • principle of least astonishment 的完美示例。
    • 这似乎是一个完全不必要的参数!如果你的块嵌套超过 2 层,你能想象一个“C”编译器会生成错误的代码吗?
    • 实际效果如何。
    猜你喜欢
    • 1970-01-01
    • 2021-12-31
    • 2021-09-04
    • 2018-08-18
    • 1970-01-01
    • 2015-03-20
    • 2015-05-25
    相关资源
    最近更新 更多