powershell - 如何验证 JSON 作为 Power shell 中字符串参数的键
问题描述
我想使用这个 JSON 从 PowerShell 进行验证
{
"Customer": {
"OnSubscription": true,
"Name": "John",
"Surname": "Smith"
},
"Data": {
"Basket": [
"apples",
"pears",
"oranges",
"strawberries"
]
}
}
这是我的脚本
$json = Get-Content .\basket.json | ConvertFrom-Json
param(
[string[]]$param = "Customer"
)
Write-Host $param
if ($param -eq $json) {
Write-Host "Valid Customer Key"}
else
{
$message = "Invalid Customer Key"
Write-Host $message
}
$output = ($json.$param.PSObject.Properties.Name | ForEach-Object {
"$_={0}" -f $json.$param.$_
}) -join "`n"
$Path2 = ".\output\env"
$output | Out-File $Path2
用于检查 JSON 的参数 create,是否有有效的客户密钥?例如,输入参数 ABC,但在 JSON 中没有 ABC。所以它会显示类似“无效的客户密钥”的消息。当条件是有效的客户密钥时,它会显示类似“有效客户密钥”的消息,但结果我总是得到“无效的客户密钥” if 条件有问题吗?
解决方案
你可能想稍微清理一下你的代码,不要考虑这么复杂。你的任务很简单,我为你模拟了一些东西。
加载我.json
{
"content":[
{
"Customer":{
"OnSubscription":true,
"Name":"John",
"Surname":"Smith"
},
"Data":{
"Basket":[
"apples",
"pears",
"oranges",
"strawberries"
]
}
},
{
"Customer":{
"OnSubscription":true,
"Name":"John2",
"Surname":"Smith"
},
"Data":{
"Basket":[
"apples",
"pears",
"oranges",
"strawberries"
]
}
},
{
"Customer":{
"OnSubscription":true,
"Name":"John3",
"Surname":"Smith"
},
"Data":{
"Basket":[
"apples",
"pears",
"oranges",
"strawberries"
]
}
}
]
}
第一步 - 将 Json 的内容放入对象中
$myJson = Get-Content -Path (Join-Path $PSScriptRoot '\loadMe.json') | ConvertFrom-json
第二步 - 遍历内容并匹配名称
foreach($item in $myJson.content) {
if($item.Customer.Name -eq $myOtherVariable) {
...
}
}
以下代码给出了想要的输出,任务完成
$myJson = Get-Content -Path (Join-Path $PSScriptRoot '\loadMe.json') | ConvertFrom-json
foreach($item in $myJson.content) {
Write-Host $item.Customer.Name
}
Output -->
John
John2
John3
推荐阅读
- leaflet - 如何在 Leaflet 中设置边界?
- java - 如何使用 RecyclerView 在适配器中设置 OnClickListener 以显示内部片段
- python - 如何在 discord.py 中获取 X-RateLimit
- flutter - 根据闭包上下文的要求,返回类型“_MainPage”不是“Widget”
- android - 获取 Google 漏洞邮件
- reactjs - 添加新数据时如何使滚动条始终粘在底部
- firebase - SafetyNet Attestation 未能通过 Flutter Firebase 电话身份验证
- android - 在非otg Android手机上激活OTG
- javascript - 如何使用 eventlistener 在 javascript 中添加多个 id?
- python - 从点云的索引向量中获取坐标向量