问题描述
我有用逗号分隔的用户输入,并且我正在使用拆分功能来获取不同的值。我有一个API,可以返回JSON中的一些数据。我想根据用户输入从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
operator的 binary 形式- 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()
接下来,必须$Obj
使用Where-Object
进行过滤,即ConvertFrom-Json
将您的JSON文本解析成的自定义对象图,而不是原始JSON:
$filteredData = $Obj.results | Where-Object id -in $userInputData
通过-in
operator,您可以测试LHS是否属于RHS阵列。
将它们放在一起:
注意:由于在.results
对象中最后一个属性后面加上逗号,我的示例JSON在技术上是无效的,我已在下面对此进行了更正。在PowerShell [Core] v6 +中,ConvertFrom-Json
甚至接受无效的JSON,但在Windows PowerShell中不接受。
# Sample user input,in lieu of the Read-Host call.
$GetIds = '1,').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
,
怎么样...
# 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"
},"name": "Mark"
},"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
#>