json - 根据用户输入 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 。谢谢
解决方案
首先,如果您想用逗号 ( )分割,请使用运算符的二进制形式-一元形式仅按空格分割。-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
推荐阅读
- javascript - Javascript无法识别新行
- php - 在 WordPress Post 编辑中限制类别列表视图
- c - 比较C中的两个二进制文件
- wordpress - Wordpress 分页在移动设备和桌面设备上不同
- jenkins - jenkins job builder - 创建列表视图时的多个正则表达式作业过滤器
- ios - 如何使用观察者?为什么我的观察员不在这里工作?
- wso2 - WSO2 企业集成器和 GraphQL
- php - 脚本 A 中的 sleep() 会允许脚本 B 运行吗?
- android - 尝试使用 FOR 循环更改按钮的背景资源时出现 NullPointerException
- rust - 一次一个字符地遍历整个文件