简体   繁体   中英

Invoke-RestMethod doesn't create PS object out of JSON

I'm trying to get some information from JSON files in order to process it with PowerShell. I use Invoke-RestMethod and basically it works:

$json = Invoke-RestMethod -Uri http://www.pgatour.com/data/r/012/leaderboard-v2.json

As a result I get a PSCustomObject and that's what I need. I can immediately access its properties and get required data. But, the same approach does not work for some JSON files, eg for http://www.pgatour.com/data/r/current/schedule-v2.json the result is not PSCustomObject, but a string.

Why does it work with one JSON and doesn't with another? They are both valid JSONs. Is there a way to get PSCustomObject out of the second JSON?

To answer the final question: Try ConvertFrom-Json to convert a JSON string to a regular PS object.

The ConvertFrom-Json cmdlet converts a JSON-formatted string to a custom object (PSCustomObject) that has a property for each field in the JSON string. ... This cmdlet is introduced in Windows PowerShell 3.0.

https://technet.microsoft.com/library/3612c3f9-2153-4a1e-aebc-3092d707d567(v=wps.630).aspx

And for completeness' sake, use ConvertTo-Json to go back the other way.


As to why it works fine with one but not another... Testing with the example URIs given here and the Convert*-Json cmdlets, the first one converts fine, but the second one does not. This may relate to why the behaviour differs between each example.

ConvertFrom-Json : Cannot process argument because the value of argument "name" is not valid. 
Change the value of the "name" argument and run the operation again.

There was something in the response from the second URI which is causing problems in the string-to-JSON conversion. The second API returns a large string (172667 characters). This is hardly huge but...

  1. this page on Reddit , shows a function that someone needed to write in order to handle longer JSON strings and,
  2. The following StackOverflow Q&A covers problems converting large JSON strings: ConvertFrom-Json max length

Using the functions/code from either of those links with the data returned by the second API does indeed produce an object:

PS> ConvertFrom-Json2 -InputObject $json2

header       : {[version, 0.0]}
_comment     : This will be replaced with a separate file in the future.
thisWeek     : {[weekNumber, 17], [startDate, 2016-04-17], [endDate, 2016-04-24]}
currentYears : {[r, 2016], [s, 2016], [h, 2016], [c, 2016]...}
years        : {System.Collections.Generic.Dictionary`2[System.String,System.Object]}

Phew!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM