从较大的PowerShell对象创建新的JSON对象

时间:2017-05-03 00:36:48

标签: json powershell

从我通过Invoke-RestMethod检索的大型PowerShell对象中,我希望将其缩小以选择属性并创建一个新的(较小的)对象,然后我可以将其转换为JSON数组。

样本集由'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

给我:

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      : 

如果我在根级属性上使用select选项,则按预期工作:

$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

输出:

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

但如果我尝试添加其中一个嵌套属性,它就不会像我希望的那样工作......

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

我想看到的内容:

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

我也试过扩展数组,但这似乎丢失了我想要保留的根级别字段:

$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"
}

任何建议/指示都非常感谢!

1 个答案:

答案 0 :(得分:0)

由TessellatingHeckler提供

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