首页 > 解决方案 > 根据用户输入 powershell 过滤 JSON

问题描述

我有用逗号分隔的用户输入,我正在使用 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 。谢谢

标签: jsonpowershellpowershell-core

解决方案


首先,如果您想用逗号 ( )分割,请使用运算符的二进制形式-一元形式仅按空格分割。-split,

# 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()

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

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

-in运算符允许您测试 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

推荐阅读