我想使用 Powershell 遞回地在 JSON 中搜索字串,然后讓它回傳值的路徑以及值是什么。
在此示例中,我想在整個 JSON 中搜索其值中包含“緊身胸衣”的任何鍵,然后回傳它是在以下位置找到的:
- Data.RootChunk.appearances[0].Data.compiledData.Data.Chunk[0].mesh.DepotPath 的值為“base\characters\garment\player_equipment\torso\t1_060_tank__corset\t1_060_pma_tank__corset.mesh”,
- Data.RootChunk.appearances[0].Data.compiledData.Data.Chunk[0].name,值為 t1_060_pma_tank__corset3513
這是 C:\myFile.json 檔案。它只是完整檔案的一部分,很長。例如,完整檔案在 Data.RootChunk.appearances[#] 內有 20 條記錄
{
"Header": {
"Version": "2022-10-28",
"JsonVersion": "0.0.3"
},
"Data": {
"Version": 195,
"BuildVersion": 0,
"RootChunk": {
"$type": "appearanceAppearanceResource",
"alternateAppearanceMapping": [],
"alternateAppearanceSettingName": 0,
"alternateAppearanceSuffixes": [],
"appearances": [
{
"HandleId": "0",
"Data": {
"$type": "appearanceAppearanceDefinition",
"censorFlags": 0,
"compiledData": {
"BufferId": "0",
"Data": {
"Version": 4,
"Sections": 7,
"CruidIndex": -1,
"CruidDict": {
"0": 2050492557716705284
},
"Chunks": [
{
"$type": "entGarmentSkinnedMeshComponent",
"acceptDismemberment": 1,
"chunkMask": 18446744073709551615,
"LODMode": "AlwaysVisible",
"mesh": {
"DepotPath": "base\\characters\\garment\\player_equipment\\torso\\t1_060_tank__corset\\t1_060_pma_tank__corset.mesh",
"Flags": "Default"
},
"meshAppearance": "military_dirty",
"name": "t1_060_pma_tank__corset3513",
"navigationImpact": {
"$type": "NavGenNavigationSetting",
"navmeshImpact": "Ignored"
},
"order": 0,
"overrideMeshNavigationImpact": 1,
"parentTransform": {
"HandleId": "1",
"Data": {
"$type": "entHardTransformBinding",
"bindName": "root",
"enabled": 1,
"enableMask": {
"$type": "entTagMask",
"excludedTags": {
"$type": "redTagList",
"tags": [
"NoBinding"
]
}
},
"slotName": 0
}
}
}
]
}
}
}
}
]
},
"forceCompileProxy": 0,
"generatePlayerBlockingCollisionForProxy": 0,
"partType": 0,
"preset": 0,
"proxyPolyCount": 1400,
"Wounds": []
}
}
我唯一的成功是讓 Powershell 顯示完整的 JSON。將 JSON 轉換為哈希表會導致其鍵值資訊丟失,并且由于某種原因,我無法使用嵌套的 foreach 或遞回函式來鉆取 JSON 結構。我對遞回函式最有希望,但它一直報告 Header 和 Data 作為結果,它甚至從未深入到第二層。
$SourceFile = 'C:\myFile.json'
$Properties = Get-Content -Path $SourceFile | ConvertTo-Json
$Properties
uj5u.com熱心網友回復:
讓我提供另一個自定義函式,Get-LeafProperty(下面的源代碼):
假設它已經定義,您可以按如下方式呼叫它:
Get-Content -Raw C:\myFile.json | ConvertFrom-Json |
Get-LeafProperty -FilterValue corset -MatchMode Substring
輸出,基于您的示例 JSON(具有和屬性的兩個[pscustomobject]實體):.Path.Value
Path Value
---- -----
Data.RootChunk.appearances[0].Data.compiledData.Data.Chunks[0].mesh.DepotPath base\characters\garment\player_equipment\torso\t1_060_tank__corset\t1_060_pma_tank__corset.mesh
Data.RootChunk.appearances[0].Data.compiledData.Data.Chunks[0].name t1_060_pma_tank__corset3513
Get-LeafProperty源代碼:
# Returns all leaf properties of an [pscustomobject] object graph
# such as returned from ConvertFrom-Json as name-path-value pairs,
# optionally filtered by a leaf value.
# You can match by full value (by default), or by substring, wildcard pattern,
# or regex, using the -MatchMode parameter. Add -CaseSensitive if needed.
# Note: A leaf property is a property whose value is neither a [pscustomobject]
# nor an array, i.e. a value converted from a JSON primitive, namely
# a string, Boolean, number, date, or $null.
function Get-LeafProperty {
[CmdletBinding(PositionalBinding = $false)]
param(
[Parameter(ValueFromPipeline, Mandatory, Position = 0)] [AllowNull()] [object] $InputObject,
[Parameter(ParameterSetName = 'Filter')] [AllowNull()] $FilterValue,
[ValidateSet('Full', 'Substring', 'Wildcard', 'Regex')]
[Parameter(ParameterSetName = 'Filter')] $MatchMode = 'Full',
[switch] $CaseSensitive,
[string] $NamePath # used internally only
)
process {
$null = $PSBoundParameters.Remove('InputObject'); $null = $PSBoundParameters.Remove('NamePath')
if ($InputObject -is [array]) {
# Recurse on the array's elements.
$i = 0
foreach ($o in $InputObject) { Get-LeafProperty -InputObject $o -NamePath ($NamePath '[' $i ']') @PSBoundParameters }
}
elseif ($InputObject -is [System.Management.Automation.PSCustomObject]) {
# A custom object: enumerate its properties / entries.
$sep = '.' * ($NamePath -ne '')
foreach ($p in $InputObject.psobject.properties) {
Get-LeafProperty -InputObject $p.Value -NamePath ($NamePath $sep $p.Name) @PSBoundParameters
}
}
else {
# A leaf property (string, Boolean, number, date, or $null).
# Report it along with its property path, but - if a filter value
# was given - only if it matches that value.
if ($PSCmdlet.ParameterSetName -eq 'Filter') {
$found = $false
switch ($MatchMode) {
'Full' {
$found = if ($CaseSensitive) { $FilterValue -ceq $InputObject } else { $FilterValue -eq $InputObject }
break
}
'Substring' {
$found =
if ($CaseSensitive) { -1 -ne "$InputObject".IndexOf($FilterValue, [StringComparison]::InvariantCulture) }
else { -1 -ne "$InputObject".IndexOf($FilterValue, [StringComparison]::InvariantCultureIgnoreCase) }
break
}
'Wildcard' {
$found = if ($CaseSensitive) { $InputObject -clike $FilterValue } else { $InputObject -like $FilterValue }
break
}
'Regex' {
$found = if ($CaseSensitive) { $InputObject -cmatch $FilterValue } else { $InputObject -match $FilterValue }
break
}
}
}
else {
$found = $true # no filtering
}
if ($found) {
[pscustomobject] @{
Path = $NamePath
Value = $InputObject
}
}
}
}
}
按屬性名稱而不是值過濾:
上面的函式只支持按屬性值直接過濾。
但是,您可以在事后使用呼叫按屬性名稱進行過濾;Where-Object例如,以下命令提取其路徑包含mesh屬性的所有路徑-值對:
Get-Content -Raw C:\myFile.json | ConvertFrom-Json |
Get-LeafProperty |
Where-Object Path -match '\bmesh\b'
輸出,帶有您的示例 JSON:
Path Value
---- -----
Data.RootChunk.appearances[0].Data.compiledData.Data.Chunks[0].mesh.DepotPath base\characters\garment\player_equipment\torso\t1_060_tank__corset\t1_060_pma_tank__corset.mesh
Data.RootChunk.appearances[0].Data.compiledData.Data.Chunks[0].mesh.Flags Default
uj5u.com熱心網友回復:
您可以使用我的函式Expand-Json來展平 JSON,并能夠使用簡單的Where-Object管道在任何地方搜索值:
Get-Content -Path $SourceFile -Raw |
ConvertFrom-Json |
Expand-Json -IndexFormat '[{0}]' |
Where-Object { $_.Value -is [string] -and $_.Value -match 'corset' } |
ForEach-Object {
'{0} with the value "{1}"' -f $_.Path, $_.Value
}
輸出:
Data.RootChunk.appearances[0].Data.compiledData.Data.Chunks[0].mesh.DepotPath with the value "base\characters\garment\player_equipment\torso\t1_060_tank__corset\t1_060_pma_tank__corset.mesh"
Data.RootChunk.appearances[0].Data.compiledData.Data.Chunks[0].name with the value "t1_060_pma_tank__corset3513"
筆記:
- 默認路徑格式使用尖括號作為陣列索引,例如
item<0>,這樣可以更輕松地使用 PowerShell 運算子進行搜索-like。在上面的示例中,引數-IndexFormat用于指定方括號,以匹配您想要的輸出。
uj5u.com熱心網友回復:
由于 Q 有jq標記,并且由于到目前為止此頁面上其他地方提出的解決方案似乎如此復雜,因此可能值得注意兩個簡單的 jq 解決方案。
paths as $p
| getpath($p) as $v
| select($v |strings|test("corset"))
| [$p, $v]
并使用-—stream命令列選項:
select(length==2 and
(.[-1]|strings|test("corset")))
您可以根據您的規格輕松定制路徑的精美列印。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/523413.html
標籤:json电源外壳搜索
上一篇:給單個輸出
