powershell 用于迭代JSON数据的递归函数

hkmswyz6  于 2022-11-10  发布在  Shell
关注(0)|答案(2)|浏览(136)

我有这个JSON对象,在PowerShell中嵌套了“Items”,我想使用递归函数遍历所有对象

[
    {
        "name":  "Introduction",
        "href":  "introduction.md"
    },
    {
        "name":  "Definitions and schema",
        "href":  "definition-and-schema/intro.md",
        "items":  [
            {
                "name":  "Entity definitions",
                "href":  "definition-and-schema/entity-definitions/intro.md",
                "items":  [
                    {
                        "name":  "Entity definitions page",
                        "href":  "definition-and-schema/entity-definitions/entity-definitions.md"
                    },
                    {
                        "name":  "Create a new Entity definition",
                        "href":  "definition-and-schema/entity-definitions/create-entity-definition.md"
                    },
                    {
                        "name":  "Member groups",
                        "href":  "definition-and-schema/entity-definitions/member-groups.md"
                    },
                    {
                        "name":  "Members",
                        "href":  "definition-and-schema/entity-definitions/members/intro.md",
                        "items":  [
                            {
                              "name":  "Adding a property",
                              "href":  "definition-and-schema/entity-definitions/members/adding-property.md"
                            },
                            {
                              "name":  "Adding a relation",
                              "href":  "definition-and-schema/entity-definitions/members/adding-relation.md"
                            },
                            {
                              "name":  "Adding a taxonomy",
                              "href":  "definition-and-schema/entity-definitions/members/adding-taxonomy.md"
                            }
                        ]
                    }
                ]
            }
        ]
    }
]

我正在使用ConvertFrom-json检索json对象

$jsonObject = ConvertFrom-Json $JsonString
bvn4nwqk

bvn4nwqk1#

以下代码片段递归地遍历对象图并处理每个"items"属性值:

$jsonObject | ForEach-Object {
    # Helper script block that walks the object graph.
    $sb = {
      foreach ($el in @($args[0])) { # iterate over elements (if an array)
        foreach ($prop in $el.psobject.Properties) { # iterate over properties
          if ($prop.Name -eq 'items') {
            # Process the "items" property value here (may be an array)
            $prop.Value 
          }
          & $sb $prop.Value  # recurse
        }
      }
    }
    # Call the script block with the input object.
    & $sb $_
  }
dgtucam1

dgtucam12#

递归地查找(和/或替换)PowerShell对象中的节点的常见可重用函数:

function Get-Node {
    [CmdletBinding()][OutputType([Object[]])] param(
        [ScriptBlock]$Where,
        [Parameter(ValueFromPipeLine = $True, Mandatory = $True)]$InputObject,
        [Int]$Depth = 9
    )
    process {
        if ($_ -isnot [String] -and $Depth -gt 0) {
            if ($_ -is [Collections.IDictionary]) {
                if (& $Where) { $_ }
                $_.get_Values() |Get-Node -Where $Where -Depth ($Depth -1)
            }
            elseif  ($_ -is [Collections.IEnumerable]) {
                for ($i = 0; $i -lt $_.get_Count(); $i++) { $_[$i] |Get-Node -Where $Where -Depth ($Depth -1) }
            }
            elseif ( $Nodes = $_.PSObject.Properties.Where{ $_.MemberType -eq 'NoteProperty'} ) {
                $Nodes.ForEach{
                    if (& $Where) { $_ }
                    $_.Value |Get-Node -Where $Where -Depth ($Depth -1)
                }
            }
        }
    }
}

使用方法

查找具体节点的值:

($jsonObject |Get-Node -Where { $_.name -eq 'Name' -and $_.value -Like '*Member*' }).Value

Member groups
Members

在哈希表的情况下:

$HashTable = ConvertFrom-Json $JsonString -AsHashTable
($HashTable |Get-Node -Where { $_.name -Like '*Member*' }).href

警告:与PowerShell的正常行为不同,哈希表kay区分大小写。

另请参阅:#14143 JSON auto-parse is case insensitive

替换特定节点的所有值:

$jsonObject |Get-Node -Where { $_.Name -eq 'href' } |
    ForEach-Object { $_.Value  = 'href://' + $_.Value }
$JsonObject |ConvertTo-Json -Depth 9

结果

[
  {
"name": "Introduction",
"href": "href://introduction.md"
  },
  {
"name": "Definitions and schema",
"href": "href://definition-and-schema/intro.md",
"items": [
  {
    "name": "Entity definitions",
    "href": "href://definition-and-schema/entity-definitions/intro.md",
    "items": [
      {
        "name": "Entity definitions page",
        "href": "href://definition-and-schema/entity-definitions/entity-definitions.md"
      },
      {
        "name": "Create a new Entity definition",
        "href": "href://definition-and-schema/entity-definitions/create-entity-definition.md"
      },
      {
        "name": "Member groups",
        "href": "href://definition-and-schema/entity-definitions/member-groups.md"
      },
      {
        "name": "Members",
        "href": "href://definition-and-schema/entity-definitions/members/intro.md",
        "items": [
          {
            "name": "Adding a property",
            "href": "href://definition-and-schema/entity-definitions/members/adding-property.md"
          },
          {
            "name": "Adding a relation",
            "href": "href://definition-and-schema/entity-definitions/members/adding-relation.md"
          },
          {
            "name": "Adding a taxonomy",
            "href": "href://definition-and-schema/entity-definitions/members/adding-taxonomy.md"
          }
        ]
      }
    ]
  }
]
  }
]

相关问题