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

后端 未结 1 2023
借酒劲吻你
借酒劲吻你 2021-01-27 19:23

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:

$jso         


        
相关标签:
1条回答
  • 2021-01-27 20:27

    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!

    0 讨论(0)
提交回复
热议问题