Home > OS >  How to easily extract the first/last element from a PSCustomObject (preferably without foreach)?
How to easily extract the first/last element from a PSCustomObject (preferably without foreach)?

Time:07-13

I have this JSON:

'{
    "fibo": {
        "2": { "hi": "there" },
        "8": { "and": "you?" }
        "5": { "well": "doing fine" },        
        "3": { "what": "is hap?" },
    }
}'

And I want for instance to extract the last element (the { "what": "is hap?" } object), in the simplest manner possible (preferably one-liner with piping, without foreach-ing it).

I tried:

'{
    "fibo": {
        "2": { "hi": "there" },
        "8": { "and": "you?" }
        "5": { "well": "doing fine" },        
        "3": { "what": "is hap?" },
    }
}' | ConvertFrom-Json | select { $_.fibo } | select -Last 1

But the select -Last 1 seems to be doing nothing.

I can use select { $_.fibo. } which works, but tomorrow that object may change to e.g.:

'{
    "fibo": {
        "2": { "hi": "there" },
        "8": { "and": "you?" }
        "5": { "well": "doing fine" },        
        "314": { "what": "is hap?" },
    }
}'

so I cannot rely on that..

CodePudding user response:

select -last 1 gives you last "fibo" object. But you already have only one object, but with 4 properties.

To get properties, you could use

    $pso = '{
        "fibo": {
            "2": { "hi": "there" },
            "8": { "and": "you?" },
            "5": { "well": "doing fine" },        
            "3": { "what": "is hap?" }
        }
    }' | ConvertFrom-Json 

# gets properties, but does not preserver order: 
$pso.fibo | Get-Member -MemberType NoteProperty

# this will preserve the order
$pso.fibo.psobject.properties

# so to get last property (it already has the name and value)
$prop = $pso.fibo.psobject.properties | select -Last 1
$prop
  • Related