ConvertTo-Json将数组扩展到3级以上 [英] ConvertTo-Json flattens arrays over 3 levels deep

查看:87
本文介绍了ConvertTo-Json将数组扩展到3级以上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在powershell中,以下内容会产生正确的结果。

In powershell, the following produces correct results.

$foo = @{}
$foo.bar = @{}
$foo.bar.buzz = @("herp","derp")
ConvertTo-Json $foo

{                                     
  "bar":  {                         
    "buzz":  [            
      "herp",  
      "derp"   
    ]            
  }                         
}

但是,如果我再添加一个级别,则将嗡嗡声数组展平为字符串

However if I add one more level, then the array "buzz" is flattened into a string

$foo = @{}
$foo.bar = @{}
$foo.bar.buzz = @{}
$foo.bar.buzz.bazz = @("herp","derp")
ConvertTo-Json $foo

{
  "bar":  {
    "buzz":  {
      "bazz": "herp derp"
    }
  }
}

为什么powershell将数组展平为字符串?
此问题感觉与以下SO问题类似,但没有一种有针对性的解决方案可以解决。

Why does powershell flatten Arrays into strings? This issue feels similar to the following SO questions, but none of the purposed solutions solves it.

为什么Powershell会悄悄地将一个字符串数组转换为带有一个项目的字符串

what-determines-whether-the -powershell-pipeline-will-unroll-a-collection

推荐答案

来自 ConvertTo-Json文档


-深度

-Depth

指定包含多少级包含的对象
JSON表示形式。默认值为2。

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

在<$>中添加 -Depth 9 选项c $ c> ConvertTo-Json 解决了这个问题

Adding -Depth 9 option to ConvertTo-Json fixes the issue

ConvertTo-Json -Depth 9 $foo

此外, ConvertTo-Json $ foo $ foo | ConvertTo-Json 。尽可能使用 ConvertTo-Json $ foo

Also, there is a difference between ConvertTo-Json $foo and $foo | ConvertTo-Json. Use ConvertTo-Json $foo whenever possible.

转换为-json-an-array-with-a-single-item

这篇关于ConvertTo-Json将数组扩展到3级以上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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