0

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?

Dean Egan
  • 3
  • 2
  • 3
    The default encoding of PowerShell prior to PowerShell 6 is unfortunately `unicode`, which means UTF-16 with a BOM -- that's the two characters. Later versions switch the default to `utf8NoBom`, which is more compatible. See [this question](https://stackoverflow.com/q/5596982/4137916) for a full treatment. Depending on what node.js will eat you might get away with `-Encoding UTF8`, or if you know your JSON will never contain characters outside ASCII `-Encoding ASCII` would do (but be careful about assumptions). If there's a way to make node.js read files with a BOM that would work too. – Jeroen Mostert Aug 24 '21 at 10:16
  • The first word in your original JSON, does it contain any special characters? – Judd Davey Aug 24 '21 at 12:06
  • Thank you very much @JeroenMostert - appending -Encoding ASCII when saving it has JSON done the trick. cheers!! – Dean Egan Aug 24 '21 at 13:20

0 Answers0