Currently im writing a function to remove from an array and then save to a database. When I write the output it does not put the wrapper (This ->[]) around the file. This makes the json file unreadable. Wondering if im missing anything
$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
Here is a copy of the working DB
[{"Date":"09/30/2021 10:19:34 -05:00","Username":"Username1000"}]
Here is what it looks like when it saves an unreadable json file
{"Date":"09/30/2021 10:19:34 -05:00","Username":"Username1000"}
Huge thanks everyone!!!
CodePudding user response:
When you pipe a single object (or a single-item array) to ConvertTo-Json
, it's going to assume that the root object is a scalar, even though it might have been contained in an array or list-like type when you piped it in (the cmdlet has no way of knowing).
In order to fix this, pass an array or list directly to the command instead of piping the input to it:
ConvertTo-Json @($script:jsonDB) -Depth $ArrayIndex -Compress | ...
Since the cmdlet now receives an explicit reference to an array (as opposed to receiving the members of the array, 1 by 1, via the pipeline), it knows that the root object should be an array too, and you'll get consistent results regardless of how many objects $script:jsonDB
contains