英文:
How can I get the Path value in this Json?
问题
{
"vaults": {
"43371adf": {
"path": "C:\Users\user23\Documents\Mango Vault",
"ts": 16767
},
"54a80cfadc691ec4": {
"path": "C:\Users\user23\Documents\Apple Vault",
"ts": 166576
},
"af524734": {
"path": "C:\Users\user23\Documents\Orange Vault",
"ts": 166985
},
"40290aab5": {
"path": "C:\Users\user23\Documents\Banana Vault",
"ts": 167293,
"open": true
}
},
"frame": "hidden"
}
<details>
<summary>英文:</summary>
I have a Json which is similar to this sample here
{
"vaults": {
"43371adf": {
"path": "C:\Users\user23\Documents\Mango Vault",
"ts": 16767
},
"54a80cfadc691ec4": {
"path": "C:\Users\user23\Documents\Apple Vault",
"ts": 166576
},
"af524734": {
"path": "C:\Users\user23\Documents\Orange Vault",
"ts": 166985
},
"40290aab5": {
"path": "C:\Users\user23\Documents\Banana Vault",
"ts": 167293,
"open": true
}
},
"frame": "hidden"
}
I am interested in retrieving the values for the keys `Path`. Some things I tried are:
$vaultsIndex = Get-Content -Path "C:\Temp\sample.json" | ConvertFrom-Json
$vaultsIndex.vaults
$vaultsIndex.vaults | foreach {$_.where -eq 'path'} #Returns 'False'
$vaultsIndex.vaults.where -eq 'path' #Also Returns 'False'
The only thing that works is `$vaultsIndex.vaults.43371adf` which I cant automate at all, I really need to just be all to get all the paths in a generic way.
The searches I performed just pointed me to this `$_.where()` method. Any help would be greatly appreciated!
</details>
# 答案1
**得分**: 4
你可以通过调用[`.PSObject.Properties`](https://learn.microsoft.com/en-us/dotnet/api/system.management.automation.psobject.properties?view=powershellsdk-7.2.0)来访问对象的属性。由于你只对`vault`中每个对象的`path`感兴趣,我们可以调用属性集的[`.Value`属性](https://learn.microsoft.com/en-us/dotnet/api/system.management.automation.psmemberinfo.value?view=powershellsdk-7.2.0#system-management-automation-psmemberinfo-value)来访问它们,然后调用每个对象上的`.path`来获取值。这是通过[成员访问枚举](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_member-access_enumeration?view=powershell-7.2)来完成的:
```powershell
$json.vaults.PSObject.Properties.Value.path
英文:
You can access an object's Properties by calling .PSObject.Properties over said object. Since you're interested only in the path of each object in vault, we can call the .Value property of the property collection to access them and from there call .path over each object to get the values. This is done via member-access enumeration:
$json.vaults.PSObject.Properties.Value.path
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论