'Powershell - json File - select only first value
I've got this json file:
[
{
"group": [313, 312, 313, 311],
"group_name": ["example", "example", "example1"],
"status": ["not_available_time", "no_time"]
}
]
And in Powershell I want the output to be: 313, example, not_available_time
So I always need just the first value.
I've tried this:
$responseJson = ConvertFrom-Json $response.Content
$group = $responseJson.group[0]
$name = $responseJson.group_name[0]
$status = $responseJson.status[0]
That works. But only if there is always more than one value.
For example: if "group_name" in the JSON file would only hold the value "example" (and not ["example", "example", "example1"]) => the output would only be "e" instead of "example". It takes not the first value, but only the first letter if there is only one value.
How can I select the first value?
BR and thanks!
Solution 1:[1]
There are 2 safe methods to ensure you're always selecting the first Value, be it an array, a scalar or null:
- You can use the array subexpression operator
@(), which will ensure that even if the value is$nullor[System.Management.Automation.Internal.AutomationNull]::Valuethe result will always be an array (object[]):
@([System.Management.Automation.Internal.AutomationNull]::Value).GetType().Name # => Object[]
@($null).GetType().Name # => Object[]
- As an alternative,
Select-Objectwith the-First 1argument, the difference is the returned object's Type remains the same:
(1 | Select-Object -First 1).GetType().Name # => Int32
('a', 'b' | Select-Object -First 1).GetType().Name # => String
$null -eq ($null, $null | Select-Object -First 1) # => True
Both alternatives are valid and depends on your use case which one fits your need better:
$json = @'
[
{
"group": [313, 312, 313, 311],
"group_name": "single_element",
"status": null
}
]
'@ | ConvertFrom-Json
$json.PSObject.Properties | ForEach-Object {
$arr = @($_.Value)[0]
$slo = $_.Value | Select-Object -First 1
[pscustomobject]@{
'ArraySubExpression' = "[ {0}: $arr ]" -f $_.Name
'Select-Object' = "[ {0}: $slo ]" -f $_.Name
}
}
ArraySubExpression Select-Object
------------------ -------------
[ group: 313 ] [ group: 313 ]
[ group_name: single_element ] [ group_name: single_element ]
[ status: ] [ status: ]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Santiago Squarzon |
