【问题标题】:Filter JSON based on the user input powershell根据用户输入 powershell 过滤 JSON
【发布时间】:2021-01-18 09:36:24
【问题描述】:

我有用逗号分隔的用户输入,我正在使用 split 函数来获取不同的值。我有一个以 JSON 格式返回一些数据的 API。我想根据用户输入过滤来自 API Json 的数据

Powershell 代码

#Get Input data
$GetIds = Read-Host -Prompt 'Enter Ids:'

#Example 1,2
#If they enter 1,2, I want results data of John and Mark
#API Call Data
$json = @'
{  
    "results": [
        {
            "id": "1", 
             "name": "John",           
        }, 
        {
             "id": "2", 
             "name": "Mark",  
        },
        {
             "id": "3", 
             "name": "Rachel",  
        }
    ]
}
'@

$Obj = ConvertFrom-Json $json

#Split by comma

$userInputData = -split $GetIds 

#Filter json with $userInputData 
$FilteredData = $json | Where-Object { $_.id -eq #loop through $userInputData }

我希望过滤后的数据返回由 userInput 数据过滤的 $json。谢谢

【问题讨论】:

    标签: json powershell powershell-core


    【解决方案1】:

    首先,如果您想用逗号 (,) 分割,请使用 -split operatorbinary 形式 - unary 形式使用 空格分割 仅限。

    # Sample user input
    $GetIds = '1, 2'
    
    # Split by ",", remove surrounding whitespace, convert to integers.
    # For brevity, there's no error handling her, 
    # so an empty / blank input wouldn't be interpreted as id 0, 
    # and input such as `'1 2'` (no comma) would break.
    [int[]] $userInputData = ($GetIds -split ',').Trim()
    

    接下来,您必须使用Where-Object 过滤$Obj,即ConvertFrom-Json 将您的JSON 文本解析成的自定义对象图,而不是原始JSON:

    $filteredData = $Obj.results | Where-Object id -in $userInputData
    

    -in operator 允许您测试 LHS 是否是 RHS 阵列的一部分。


    把它们放在一起:

    注意:您的示例 JSON 在技术上是无效的,因为 .results 对象中最后一个属性后面的尾随逗号,我在下面更正了。在 PowerShell [Core] v6+ 中,ConvertFrom-Json 甚至可以接受无效的 JSON,但在 Windows PowerShell 中则不行。

    # Sample user input, in lieu of the Read-Host call.
    $GetIds = '1, 2'
    
    # Split by ",", remove surrounding whitespace, convert to integers.
    # For brevity, there's no error handling her, 
    # so an empty / blank input wouldn't be interpreted as id 0, 
    # and input such as `'1 2'` (no comma) would break.
    [int[]] $userInputData = ($GetIds -split ',').Trim()
    
    $Obj = ConvertFrom-Json @'
    {  
        "results": [
            {
                "id": "1", 
                 "name": "John"
            }, 
            {
                 "id": "2", 
                 "name": "Mark"
            },
            {
                 "id": "3", 
                 "name": "Rachel"
            }
        ]
    }
    '@
    
    $filteredData = $Obj.results | Where-Object id -in $userInputData
    
    # Output the matching objects
    $filteredData
    

    以上产出:

    id name
    -- ----
    1  John
    2  Mark
    

    【讨论】:

      【解决方案2】:

      怎么样...

      # You can split on the read
      $GetIds = (Read-Host -Prompt 'Enter Ids') -split (',')
      # Results
      <#
      1
      2
      #>
      
      # Your JSON string was not valid
      <#
      Error: Parse error on line 4:
      ...     "name": "John",     },      {           "id": "2",
      ----------------------^
      Expecting 'STRING', got '}'
      #>
      
      # Corrected, notice the removed comma after the names 
      $json = @'
      {  
          "results": [
              {
                  "id": "1", 
                   "name": "John"           
              }, 
              {
                   "id": "2", 
                   "name": "Mark"  
              },
              {
                   "id": "3", 
                   "name": "Rachel"  
              }
          ]
      }
      '@
      
      $Obj = $json | ConvertFrom-Json
      

      不需要这个...

      $userInputData = -split $GetIds 
      

      ...因为拆分是在读取上

      # Filter json with $userInputData 
      $Obj.results | 
      Where-Object id -in $GetIds
      # Results
      <#
      id name
      -- ----
      1  John
      2  Mark
      #>
      

      【讨论】:

      • 如果您没有注意到我的答案,我鼓励您现在就阅读它。假设您已经这样做了:我真的很好奇:您认为您的答案添加了哪些内容尚未包含在已接受的答案中?
      猜你喜欢
      • 1970-01-01
      • 2018-11-05
      • 2016-11-19
      • 2017-09-24
      • 1970-01-01
      • 1970-01-01
      • 2017-09-30
      • 1970-01-01
      • 2018-07-28
      相关资源
      最近更新 更多