如何在powershell中解析json响应 [英] how to parse json response in powershell
问题描述
设法获取JSON数据
$R= Invoke-WebRequest -Uri $url -Headers $headers -ContentType "application/json" -Method Get -UseBasicParsing
$x = $R.Content | Out-String | ConvertFrom-Json
现在我有一个像这样的JSON文件:
now I've a JSON file like this :
{
"id": 1000,
"name_with_namespace": "myProjectName1",
},
{
"id": 1001,
"name_with_namespace": "myProjectName2",
},
{
"id": 1002,
"name_with_namespace": "myProjectName3",
}
现在我需要提取name_with_namespace
和id
所有出现的地方 name_with_namespace=myProjectName。*
now I need to extract all the occurence of "name_with_namespace"
and "id"
where "name_with_namespace" = "myProjectName.*"
如何一次性完成?
我试过这个:
foreach ($name in $x.name_with_namespace) {
if ( $name -match ".*myProjectName.*" ) {
write-host "$name - $x.id"
}
}
但我得到了这个:
myProjectName1 1000 1001 1002
myProjectName2 1000 1001 1002
myProjectName3 1000 1001 1002
我明白问题出在$ x.id上,我怎么能得到正确的价值而不是一切?
I understand that the issue is on $x.id, how can I get the right value instead of everything ?
我的预期输出是
myProjectName1 1000
myProjectName2 1001
myProjectName3 1002
推荐答案
你正在钻探在定义循环时,将某个级别降低太多。只需迭代 $ x
然后检查循环内的特定属性。
You're drilling down a level too far when you define your loop. Just iterate $x
and then check against the specific property inside the loop.
foreach ($name in $x) {
if ( $name.name_with_namespace -match ".*myProjectName.*" ) {
write-host "$($name.name_with_namespace) - $($name.id)"
}
}
编辑: 在旁注中,您可以将 -match
简化为myProjectName
,它会起作用同样,也许更快。
On a side note, you can simplify your -match
to just "myProjectName"
and it will work just as well, and probably faster.
这篇关于如何在powershell中解析json响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!