Arrjo
Arrjo

Reputation: 31

Creating new JSON objects from larger PowerShell objects

From a large PowerShell Object that I have retrieved via an Invoke-RestMethod, I am looking to shrink this down to select attributes and create a new (smaller) object that I can then convert into a JSON array.

Sample set courtesy of 'The Scripting Guy':

$request = 'http://musicbrainz.org/ws/2/artist/5b11f4ce-a62d-471e-81fc-a69a8278c7da?inc=aliases&fmt=json'
$output = Invoke-WebRequest $request | ConvertFrom-Json
$output

Gives me:

type-id        : e431f5f6-b5d2-343d-8b36-72607fffb74b
name           : Nirvana
ipis           : {}
disambiguation : 90s US grunge band
country        : US
life-span      : @{end=1994-04-05; ended=True; begin=1988-01}
sort-name      : Nirvana
isnis          : {0000000123486830}
aliases        : {@{name=Nirvana US; type-id=; sort-name=Nirvana US; end=; 
begin=; primary=; type=; locale=; ended=False}}
begin_area     : @{name=Aberdeen; disambiguation=; sort-name=Aberdeen; 
id=a640b45c-c173-49b1-8030-973603e895b5}
area           : @{sort-name=United States; id=489ce91b-6658-3307-9877-795b68554c98; iso-3166-1-codes=System.Object[]; disambiguation=; name=United States}
type           : Group
id             : 5b11f4ce-a62d-471e-81fc-a69a8278c7da
end_area       : 
gender         : 
gender-id      : 

If I use the select option on the root-level attributes, this works as expected:

$request = 'http://musicbrainz.org/ws/2/artist/5b11f4ce-a62d-471e-81fc-
a69a8278c7da?inc=aliases&fmt=json'
$output = Invoke-WebRequest $request | ConvertFrom-Json
$output | select name, disambiguation | ConvertTo-Json

Output:

{
    "name":  "Nirvana",
    "disambiguation":  "90s US grunge band"
}

But if I try to add one of the nested attributes, it doesn't work as I'd hope...

$output | select name, disambiguation, area.sortname | ConvertTo-Json
{
    "name":  "Nirvana",
    "disambiguation":  "90s US grunge band",
    "area.sort-name":  null # <-- Expect "United States"
}

What I'd like to see:

{
    "name":  "Nirvana",
    "disambiguation":  "90s US grunge band",
    "area":  {
        "sort-name":  "United States"
    }
}

I've also tried expanding the array, but this seems to lose my root level fields which I want to retain:

$output | select -expand area | select name, disambiguation, sort-name | ConvertTo-Json
{
    "name":  "United States", # <-- Taken from the area.name value
    "disambiguation":  "",    # <-- Lost when expanding
    "sort-name":  "United States"
}

Any suggestions/pointers greatly appreciated!

Upvotes: 2

Views: 2555

Answers (1)

Arrjo
Arrjo

Reputation: 31

As provided by TessellatingHeckler

select name, @{Name='sort-name'; Expression={$_.area.{sort-name}}}

Upvotes: 1

Related Questions