gpt4 book ai didi

json - 从成功的 Invoke-RestMethod 中选择对象数据失败

转载 作者:行者123 更新时间:2023-12-03 00:27:22 27 4
gpt4 key购买 nike

我正在使用 Invoke-RestMethod -Uri https://... 调用休息服务电话。 .调用结果,位于 JSON , 可以通过管道将数据传输到 Format-Table -Property ...并显示数据。

但是当Select-Object -Property ...在调用后使用相同的参数,PSObject有列但没有数据。如果我使用不同的网络服务,调用将起作用。

enter image description here

什么可能导致 PSObject不显示任何值?

公共(public)休息网络服务的工作示例

Invoke-RestMethod -Uri https://jsonplaceholder.typicode.com/todos/1 |
Select-Object -Property title

结果
@{title=delectus aut autem}

新故障不同的 API
Invoke-RestMethod -Uri https://cat-fact.herokuapp.com/facts | Select-Object -Property text

enter image description here

最佳答案

在转换 JSON 数组时,您偶然发现了两个 PowerShell 怪异的邪恶组合:

  • Invoke-RestMethodConvertFrom-Json通过管道发送从 JSON 转换而来的数组作为一个整体,而不是像往常一样逐个元素发送 :
  • 备注 : 在 PowerShell(核心)7.0 , ComvertFrom-Json的行为已更改 与通常的元素枚举行为一致,以及 -NoEnumerate switch 被添加为对旧行为的选择。有关导致此更改的讨论,请参阅 GitHub issue #3424 .
  • 但是,在撰写本文时 (PowerShell (Core 7.2) Invoke-RestMethod 仍然表现出这种意外行为 ,这在 GitHub issue #15272 中进行了讨论。

  • Select-Object不执行member-access enumeration ,因此它直接在数组中查找指定的属性(例如 text ),但它不存在。

  • 演示问题举个简单的例子:
    # Windows PowerShell only:
    # Because ConvertFrom-Json sends an *array* (of 2 custom objects) through
    # the pipeline, Select-Object looks for property .text on the *array* -
    # and can't find it.
    # The same applies to Invoke-RestMethod (also still in
    # PowerShell (Core) as of v7.2)
    PS> ConvertFrom-Json '[{ "text": "a" }, { "text": "b" }]' | Select-Object text

    text
    ----
    # NO VALUES
    一个 简单的解决方法是附上 ConvertFrom-Json/ Invoke-RestMethod来电 (...) ,这会强制枚举数组,导致 Select-Object按预期工作。:
    # (...) forces enumeration
    PS> (ConvertFrom-Json '[{ "text": "a" }, { "text": "b" }]') | Select-Object text

    text
    ----
    a
    b
    请注意, Select-Object -Property text 之类的命令(没有 -ExpandProperty )仍然输出具有 .text 的自定义对象属性,而不是 .text属性值。
    如果您只对属性值感兴趣 ,解决方案更简单,因为可以直接在数组上使用上面提到的成员访问枚举:
    # Using .<propName> on an array (collection) implicitly returns the
    # property values from the *elements* of that collection (member-access enumeration).
    PS> (ConvertFrom-Json '[{ "text": "a" }, { "text": "b" }]').text
    a
    b
    注意输出现在没有 text header ,因为输出的只是字符串值,而不是自定义对象。

    关于json - 从成功的 Invoke-RestMethod 中选择对象数据失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56916962/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com