I have user input which is separated by commas and I am using split function to get different values. I have an API that returns some data in JSON. I want to filter data from API Json based on the user input
Powershell code
#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 }
I want the filtered data to return $json filtered by the userInput data. Thank you
First, use the binary form of the
-split
operator if you want to split by commas (,
) - the unary form splits by whitespace only.Next, it is
$Obj
that you must filter withWhere-Object
, i.e. the custom-object graph thatConvertFrom-Json
parsed your JSON text into, not the raw JSON:The
-in
operator allows you to test the LHS for being part of the RHS array.To put it all together:
Note: Your sample JSON is technically invalid, due to trailing commas after the last property in the
.results
objects, which I've corrected below. In PowerShell [Core] v6+,ConvertFrom-Json
would accept even the invalid JSON, but not in Windows PowerShell.The above yields: