【问题标题】:Powershell does not output wrapper brackets when saving json file保存json文件时Powershell不输出包装括号
【发布时间】:2021-11-24 23:02:09
【问题描述】:

目前我正在编写一个从数组中删除然后保存到数据库的函数。当我编写输出时,它不会在文件周围放置包装器(This -> [])。这使得 json 文件不可读。想知道我是否遗漏了什么

    $ArrayIndex = $script:jsonDB.username.IndexOf($UserNametextBox.text)
    $script:jsonDB = $script:jsonDB | Where-Object{$_ -ne $script:jsonDB[$ArrayIndex]}
    $script:jsonDB | ConvertTo-Json -Depth $ArrayIndex -Compress|
    Set-Content C:\Support\HardwareCollection.json
    $script:TableData = New-Object System.Collections.ArrayList
    $script:TableData.AddRange($script:jsonDB)
    $script:datagridview.DataBindings.DefaultDataSourceUpdateMode = 0 
    $script:datagridview.DataSource= $script:TableData
    $script:datagridview.Refresh

这是工作数据库的副本

[{"Date":"09/30/2021 10:19:34 -05:00","Username":"Username1000"}]

这是保存不可读的 json 文件时的样子

{"Date":"09/30/2021 10:19:34 -05:00","Username":"Username1000"}

非常感谢大家!!!

【问题讨论】:

    标签: json database powershell


    【解决方案1】:

    当您通过管道将单个对象(或单项数组)传递给 ConvertTo-Json 时,它会假设根对象是一个标量,即使它可能包含在一个数组或类似列表的类型中您通过管道输入(cmdlet 无法知道)。

    为了解决这个问题,请将数组或列表直接传递给命令,而不是通过管道将输入传递给它:

    ConvertTo-Json @($script:jsonDB) -Depth $ArrayIndex -Compress | ...
    

    由于 cmdlet 现在接收到对数组的显式引用(与通过管道一一接收数组成员相反),它知道根对象也应该是一个数组,您将无论$script:jsonDB 包含多少对象,都能获得一致的结果

    【讨论】:

    • 感谢您的帮助,这立即解决了我的问题!!!
    猜你喜欢
    • 1970-01-01
    • 2019-08-27
    • 2019-11-08
    • 2022-11-22
    • 2021-08-24
    • 1970-01-01
    • 2018-07-07
    • 1970-01-01
    • 2013-02-17
    相关资源
    最近更新 更多