I use the following PowerShell code to read in a JSON file, convert the objects from JSON file and add them to an array variable (JSON file could be empty so array variable could remain empty), then add an object to that array, then convert the array back into JSON and store the JSON file again.
Here is the code:
[System.Collections.ArrayList]$eventStartList =@()
$EventStart = Get-Content 'C:\scheduledEventStart.json' | Out-String | ConvertFrom-Json
$eventStartList += $EventStart
$eventStartList += $j #j being the new object i.e. [{"server": "server1", "name": "user1", "date": "10-10-21"}]
$eventStartList | ConvertTo-Json | Out-File 'C:\scheduledEventStart.json'
This seems to work just fine until I read the scheduledEventStart.json file in a NodeJS script. When I try to JSON parse scheduledEventStart I get an "unexpected token in JSON at position 0" message. After printing out the stringified version of scheduledEventStart.json I saw why I was getting this error. Here is the stringified version:
��{
"server_name": "server1",
"user": "user1",
"date": "2021-08-22"
}
Does anyone know why PowerShell adds the two strange characters before the { when it exports objects to JSON?