jsonpowershellinvoke-webrequestbytestream

Parsing a JSON Byte Stream Returned from a Web Request using Powershell without writing to a file


I'm using the following Powershell to call a URL that returns a JSON file. (If you were to paste the URL into the browser it would download a file, rather than display the raw JSON):

$fileName = "output.json"
$url = "https://some-url-that-returns-a-json-file-byte-stream"
$jsonFileResponse = Invoke-WebRequest -Method GET -Uri $url -UseDefaultCredentials -OutFile "output.json"
$parsedData = Get-Content -Path $fileName | ConvertFrom-Json

This works fine, and I get my parsed data at the end.

I was wondering, is there a way of doing this without involving the file system, i.e. without having the step of outputting to output.json first, and instead handling this in-memory and without any disk i/o?


Solution

  • The question is less one of converting to 'JSON' and more of just converting to text.

    Using [System.Text.Encoding]::ASCII.GetString seems to do the trick.

    $url = "https://some-url-that-returns-a-json-file-byte-stream"
    $jsonFileResponse = Invoke-WebRequest -Method GET -Uri $url -UseDefaultCredentials 
    $parsedData = [System.Text.Encoding]::ASCII.GetString($jsonFileResponse.Content) | ConvertFrom-Json