【问题标题】:Invoke-RestMethod doesn't create PS object out of JSONInvoke-RestMethod 不会从 JSON 中创建 PS 对象
【发布时间】:2018-11-09 07:22:28
【问题描述】:

我正在尝试从 JSON 文件中获取一些信息,以便使用 PowerShell 对其进行处理。 我使用 Invoke-RestMethod 并且基本上可以正常工作:

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

因此,我得到了一个 PSCustomObject,这就是我所需要的。我可以立即访问它的属性并获取所需的数据。 但是,相同的方法不适用于某些 JSON 文件,例如为了 http://www.pgatour.com/data/r/current/schedule-v2.json 结果不是 PSCustomObject,而是一个字符串。

为什么它适用于一种 JSON 而不适用于另一种?它们都是有效的 JSON。有没有办法从第二个 JSON 中获取 PSCustomObject?

【问题讨论】:

    标签: json powershell


    【解决方案1】:

    回答最后一个问题:尝试ConvertFrom-Json 将 JSON 字符串转换为常规 PS 对象。

    ConvertFrom-Json cmdlet 将 JSON 格式的字符串转换为 具有每个字段的属性的自定义对象 (PSCustomObject) JSON 字符串。 ... 此 cmdlet 在 Windows PowerShell 中引入 3.0.

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

    为了完整起见,请使用 ConvertTo-Json 以另一种方式返回。


    至于为什么它适用于一个而不是另一个...使用此处给出的示例 URI 和 Convert*-Json cmdlet 进行测试,第一个转换得很好,但第二个没有。这可能与每个示例之间的行为不同的原因有关。

    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.
    

    第二个 URI 的响应中有一些内容导致字符串到 JSON 的转换出现问题。第二个 API 返回一个大字符串(172667 个字符)。这不是很大,但是...

    1. this page on Reddit,展示了一个人需要编写的函数,以便处理更长的 JSON 字符串,并且,
    2. 以下 StackOverflow 问答涵盖了转换大型 JSON 字符串的问题:ConvertFrom-Json max length

    使用来自这些链接的函数/代码与第二个 API 返回的数据确实会产生一个对象:

    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]}
    

    呼!

    【讨论】:

    • 很高兴听到。我可能会收紧答案的措辞,以便其他人遇到同样的问题时更容易,并且可能不会过分依赖 Reddit 链接在未来的工作。
    猜你喜欢
    • 2015-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-16
    • 2015-02-04
    • 2022-11-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多