使用PowerShell解析Web请求返回的JSON字节流且无需写入文件的实现方法
完全可以实现全程内存处理,无任何磁盘I/O操作,以下是两种常用实现方案:
方案1:使用Invoke-RestMethod(推荐)
Invoke-RestMethod是PowerShell专门为REST接口请求设计的内置cmdlet,会自动识别响应中的JSON格式并直接解析为PowerShell对象,无需额外的文件操作和手动转换步骤,代码最为简洁:
$url = "https://some-url-that-returns-a-json-file-byte-stream" $parsedData = Invoke-RestMethod -Method GET -Uri $url -UseDefaultCredentials
方案2:保留Invoke-WebRequest用法
如果你需要获取完整的响应信息(比如响应头、状态码等附加数据),可以去掉-OutFile参数,直接读取内存中响应对象的Content属性进行转换即可:
$url = "https://some-url-that-returns-a-json-file-byte-stream" $jsonFileResponse = Invoke-WebRequest -Method GET -Uri $url -UseDefaultCredentials $parsedData = $jsonFileResponse.Content | ConvertFrom-Json
两种方案都不会产生任何磁盘写入/读取操作,所有处理过程均在内存中完成。
内容的提问来源于stack exchange,提问作者Mutation Person
相关产品推荐
相关产品推荐

