【发布时间】:2021-12-28 09:56:55
【问题描述】:
我创建了一个 PowerShell 脚本来从包含 JSON 数据的 Web URL 返回值。
我的脚本现在返回包含一些 JSON 数据的 HTML。
现在,我想从这个 HTML 中包含的 JSON 数据中检索一个值。
具体来说,声明数据变量的“ID.ad_user”的值(“var data =”)。
所以,“345345-3453-gfdd-44334”是我需要的值(不包括“ad_user://”文本)。
这是我的 PowerShell 代码:
$cred = "[my unique token]"
$headers = @{ Authorization = "Bearer $cred" }
$Output = Invoke-RestMethod `
-Method Get `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-Uri "[my URL]"
$Output
这是 HTML 和 JSON 输出:
<!DOCTYPE html>
<!-- If you are reading this, there is a good chance you would prefer sending an
"Accept: application/json" header and receiving actual JSON responses. -->
<link rel="stylesheet" type="text/css" href="/ui.min.css" />
<script src="/ui.min.js"></script>
<script>
var user = "admin";
var curlUser='[HIDDEN]';
var data = {"name": "Pat McKinnon","ID": ["ad_user://345345-3453-gfdd-44334","local://p-345dd455"],"state": "active",}
</script>
【问题讨论】:
-
“这是 JSON 输出”——这不是 JSON,而是 HTML...
-
@Mathias R. Jessen - 没错。我应该说包含其中包含 JSON 数据的 HTML 输出。让我更新一下。
-
你看到实际 HTML 中的注释了吗?
If you are reading this, there is a good chance you would prefer sending an "Accept: application/json" header and receiving actual JSON responses.那么为什么不这样做呢,接收的不是嵌入了 JSON 的 HTML,而是你可以使用ConvertFrom-Json的 JSON 响应。 -
感谢西奥。我将如何实现 ConvertFrom-Json 我的代码?你能分享一个例子吗?
-
可能通过将其添加到标题哈希表中:
$headers = @{ Authorization = "Bearer $cred"; Accept = "application/json" }。然后看看$Output在Invoke-RestMethod之后显示的内容。如果这确实是 JSON,您可以简单地执行$Output | ConvertFrom-Json并从那里开始工作
标签: json powershell