Reputation: 1805
Note: this question is here for historical reasons or for users of Powershell < 6.0.0. This problem should not occur in Powershell 6 and beyond.
I'm trying to use the powershell cmdlet Invoke-RestMethod
to print a json endpoint to the console.
The command executes successfully but the end result is a terminal table containing all of the json's level 1 fields.
I'm running the cmdlet like this:
Invoke-RestMethod -Uri <some url here> -Method GET -ContentType "application/json"
And getting something like this:
sections _links
-------- ------
{@{rel=parent; href=https://us9.api.mailchimp.com/3.0/templates/138...
How do I get it to just print the raw response to the terminal without formatting?
Upvotes: 21
Views: 68491
Reputation: 473
My Powershell version is 5.1.x in Windows 11. First answer is giving me an error as the request contains Body tag with JSON -
iwr -Method POST -Uri $uri -Body @{ ... } | ConvertTo-Json -Depth 10
ConvertTo-Json : An item with the same key has already been added.
But when I filter the response with the content method using -UseBasicParsing parameter and finally include ConvertTo-Json, the JSON format is the perfect to parse within a powershell script -
(iwr -Method POST -Uri $uri -UseBasicParsing -Body @{ ... } ).Content | ConvertTo-Json -Depth 10
Upvotes: 0
Reputation: 2381
The other answer works great for JSON responses, but the -UseBasicParsing switch works for any response type:
(Invoke-WebRequest -UseBasicParsing -Uri 'http://example.com').Content
will give you just the response content (in the example.com case, the raw html, or in your use case, the raw JSON).
Upvotes: 10
Reputation: 72151
First of all, the -Method
and -ContentType
you are providing are the default, you can drop those. And to get the json, cast it back to json.
Invoke-RestMethod -Uri "http://example.com/" | ConvertTo-Json -Depth 10
I have no idea why you want to cast back to json, but well, here you go.
Upvotes: 24