【问题标题】:Add json object to empty json array (powershell)将 json 对象添加到空 json 数组(powershell)
【发布时间】:2020-09-25 04:18:02
【问题描述】:

我有以下 ps/json:

$a = '[{"Type":"1","Name":"A"},{"Type":"2","Name":"B"}]'
$ps = $a | ConvertFrom-Json
Type Name
---- ----
1    A
2    B

#Now, I want to add this array into another array, so the resulting json should look like this:
[[{"Type":"1","Name":"A"},{"Type":"2","Name":"B"}]]

Remove-TypeData System.Array #needed for workaround for powershell bug: https://stackoverflow.com/questions/20848507/why-does-powershell-give-different-result-in-one-liner-than-two-liner-when-conve/38212718#38212718

$w = @()
$w += , $ps
$w |ConvertTo-Json
[
    {
        "Type":  "1",
        "Name":  "A"
    },
    {
        "Type":  "2",
        "Name":  "B"
    }
]


#It's apparent that the $ps object was NOT added to an empty array as desired, however when multiple instances are added ($w += , $ps twice for example) it works as expected:

[
    [
        {
            "Type":  "1",
            "Name":  "A"
        },
        {
            "Type":  "2",
            "Name":  "B"
        }
    ],
    [
        {
            "Type":  "1",
            "Name":  "A"
        },
        {
            "Type":  "2",
            "Name":  "B"
        }
    ]
]

所以看起来数组在那里但是外部括号没有被返回(因为它们应该是)

我已经阅读了其他问题,但找不到解决方案,如果有人能够分享?

【问题讨论】:

    标签: json powershell


    【解决方案1】:

    为避免混淆,在这种情况下最好避免使用管道(其中数组总是枚举):

    $ps = '[{"Type":"1","Name":"A"},{"Type":"2","Name":"B"}]' | ConvertFrom-Json
    
    # Wrap $ps in a single-element array.
    $w = , $ps
    
    # Workaround for Windows PowerShell:
    # See https://stackoverflow.com/a/38212718/45375
    Remove-TypeData -ErrorAction Ignore System.Array
    
    # Pass the wrapper array via -InputObject to prevent enumeration.
    ConvertTo-Json -InputObject $w -Compress
    

    以上产出:

    [[{"Type":"1","Name":"A"},{"Type":"2","Name":"B"}]]
    

    【讨论】:

      猜你喜欢
      • 2015-09-03
      • 1970-01-01
      • 2018-07-20
      • 2012-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-28
      • 2016-04-20
      相关资源
      最近更新 更多