【问题标题】:Extract Values From Raw JSON Using Powershell使用 Powershell 从原始 JSON 中提取值
【发布时间】: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" }。然后看看$OutputInvoke-RestMethod 之后显示的内容。如果这确实是 JSON,您可以简单地执行 $Output | ConvertFrom-Json 并从那里开始工作

标签: json powershell


【解决方案1】:

也许这会奏效。搜索包含 JSON 数据的字符串部分,然后转换为对象。

$result = $Output | Select-String -Pattern "var data = {.+}`n"
$lineWithData = $result.Matches.Value
$lineWithData
$json = $lineWithData.Substring('var data = '.Length)
$json
$dataObject = $json | ConvertFrom-Json
$dataObject

然后就可以从对象中获取ID属性了。

$dataObject.ID
ad_user://345345-3453-gfdd-44334
local://p-345dd455```

【讨论】:

  • 我在运行时收到以下错误:''' 您不能在空值表达式上调用方法。在 line:12 char:1 + $json = $lineWithData.Substring('var data = '.Length) '''
  • 听起来$Output 变量不包含具有预期模式的字符串,导致零匹配,因此变量$lineWithData 为空。
猜你喜欢
  • 2018-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多