json - 如何使用 Powershell 遍历 JSON 属性

标签 json powershell elasticsearch

我正在尝试使用 Powershell 访问 JSON 对象的特定属性值。不幸的是,我不知道结构中某些父属性的键,所以我不能直接这样做。此外,由于 JSON 不是数组,我无法通过索引位置访问。

上下文是我正在从 elasticsearch 查询正在运行的任务列表,需要获取任务的 ID(我知道只有一个),这样我就可以进行后续调用以发现其完成状态。

我研究了一些查询方法,但不确定如何应用它们(PowerShell 语法对我来说很新)。

我正在使用的 JSON 响应如下所示;

  "nodes" : {
    "oTUltX4IQMOUUVeiohTt8A" : {
      "name" : "H5dfFeA",
      "transport_address" : "127.0.0.1:9300",
      "host" : "127.0.0.1",
      "ip" : "127.0.0.1:9300",
      "tasks" : {
        "oTUltX4IQMOUUVeiohTt8A:124" : {
          "node" : "oTUltX4IQMOUUVeiohTt8A",
          "id" : 124,
          "type" : "direct",
          "action" : "cluster:monitor/tasks/lists[n]",
          "start_time_in_millis" : 1458585884904,
          "running_time_in_nanos" : 47402,
          "cancellable" : false,
          "parent_task_id" : "oTUltX4IQMOUUVeiohTt8A:123"
        }
      }
    }
  }
}

使用这个给定的结构,我希望能够访问第一个“任务”的 ID 属性。

因此,如果我知道 Prop 键,它将是:

nodes.oTUltX4IQMOUUVeiohTt8A.tasks.oTUltX4IQMOUUVeiohTt8A:124.id

如何在事先不知道 key 的情况下访问此值?

非常感谢任何帮助。

谢谢 尼克

最佳答案

以下代码定义并使用了函数Get-FirstPropertyValue,它执行递归、深度优先搜索对象图中的第一个属性,该属性具有一个给定的名字并返回它的值,假设该值是非空的:

# Function that returns the value of the first property with the given 
# name found during recursive depth-first traversal of the given object.
# Note that null-valued properties are ignored.
function Get-FirstPropertyValue($obj, $propName) {
  $propNames = $obj.psobject.properties.Name
  if ($propName -in $propNames) {
    $obj.$propName
  } else {
    foreach ($iterPropName in $propNames) {
        if ($null -ne ($val = Get-FirstPropertyValue $obj.$iterPropName $propName)) {
          return $val
        }
      }
  }
}

# Input JSON
$json = @'
{
    "nodes": {
        "oTUltX4IQMOUUVeiohTt8A": {
            "name": "H5dfFeA",
            "transport_address": "127.0.0.1:9300",
            "host": "127.0.0.1",
            "ip": "127.0.0.1:9300",
            "tasks": {
                "oTUltX4IQMOUUVeiohTt8A:124": {
                    "node": "oTUltX4IQMOUUVeiohTt8A",
                    "id": 124,
                    "type": "direct",
                    "action": "cluster:monitor/tasks/lists[n]",
                    "start_time_in_millis": 1458585884904,
                    "running_time_in_nanos": 47402,
                    "cancellable": false,
                    "parent_task_id": "oTUltX4IQMOUUVeiohTt8A:123"
                }
            }
        }
    }
}
'@

# Convert the JSON to a [pscustomobject] graph with ConvertFrom-Json.
$objFromJson = $json | ConvertFrom-Json

# Using the function defined above, get the first 'tasks' object found
# during recursive depth-first traversal.
$tasks = Get-FirstPropertyValue $objFromJson 'tasks'

# Get the name of the resulting object's first property.
$propName = @($tasks.psobject.properties.Name)[0]

# Extract the .id property from the object stored in the first property.
$tasks.$propName.id

以上结果:

124

更简洁但更晦涩且可能更慢的替代方案将 JSON 输入转换为 XML,然后使用 XPath 对其进行查询:

# Input JSON
$json = @'
{
    "nodes": {
        "oTUltX4IQMOUUVeiohTt8A": {
            "name": "H5dfFeA",
            "transport_address": "127.0.0.1:9300",
            "host": "127.0.0.1",
            "ip": "127.0.0.1:9300",
            "tasks": {
                "oTUltX4IQMOUUVeiohTt8A:124": {
                    "node": "oTUltX4IQMOUUVeiohTt8A",
                    "id": 124,
                    "type": "direct",
                    "action": "cluster:monitor/tasks/lists[n]",
                    "start_time_in_millis": 1458585884904,
                    "running_time_in_nanos": 47402,
                    "cancellable": false,
                    "parent_task_id": "oTUltX4IQMOUUVeiohTt8A:123"
                }
            }
        }
    }
}
'@

$parent = 'tasks'
$prop = 'id'
$propType = 'int'

$json | 
  ConvertFrom-Json |
    ConvertTo-Xml -Depth ([int]::MaxValue) | 
      Select-Xml "//Property[@Name='$parent']/*/*[@Name='$prop']/text()" |
        ForEach-Object { $_.Node.InnerText -as $propType }

关于json - 如何使用 Powershell 遍历 JSON 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58477259/

相关文章:

elasticsearch - Elastic Search截取总分中的hits.total

jquery - 在 Jquery 数据表中加载异步数据

Powershell 的 AddSslCertificate() 不适用于 IIS 10(非服务器)绑定(bind)

PowerShell 使用字符串数组查找和替换

powershell - 在 Powershell 中,仅使用内存(没有可用的磁盘存储),如何创建大型文本文件的 zip 存档并将其附加到电子邮件中?

elasticsearch - 用于生产部署的 bitnami elasticsearch helm 图表与官方弹性 helm 图表与 ECK

javascript - Express.js collection.find() 返回对象

simdjson 库未捕获 C++ 异常

json - 带有桑格利亚汽酒的 GraphQL 模式

spring-boot - 使用@RunWith(SpringJUnit4ClassRunner.class)运行文本案例时获取异常。如何解决这个问题?