Reputation: 125292
I'm trying to download a json file from a url and convert it to a json object using following code which throws an exception:
[System.Text.Encoding]::Default.GetString((Invoke-WebRequest $url).Content) |
ConvertFrom-Json
It throws:
ConvertFrom-Json : Invalid JSON primitive: ï
It throws the same exception if I use Unicode
or UTF8
.
But if I download the file using browser and look for the character in the file, there is no such character in the file. Also if you try to convert the saved file to json object, it works properly:
Get-Content $localFilePath | ConvertFrom-Json
Why do I receive this exception?
How can I get the file content without saving to a file and pass to ConvertFrom-Json
without problem?
Upvotes: 0
Views: 7049
Reputation: 125292
To solve the problem, you can use:
[System.Net.WebClient]::new().DownloadString($url) | ConvertFrom-Json
The problem is because of existence of BOM(U+FEFF byte order mark) character at beginning of a file encoded with UTF8. If you get the content of the file from url this way:
[System.Text.Encoding]::Default.GetString((Invoke-WebRequest $url).Content)
You will see 
at beginning of the file while when saving it using browser, you can not see such sequence.
Upvotes: 3