首页 > 解决方案 > 如何验证 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 条件有问题吗?

标签: powershell

解决方案


你可能想稍微清理一下你的代码,不要考虑这么复杂。你的任务很简单,我为你模拟了一些东西。

加载我.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

推荐阅读