Reputation: 65
Trying to get all the elements out of an object by knowing one element
var:[
{
name:"ben",
age:"24"
},
name:"chris",
age:"35"
}
]
want to get age by name inside of the particular object
name:"ben",
age:"24"
Upvotes: 0
Views: 31
Reputation: 25061
If you are working with a properly formatted JSON file, you can do the following:
$json = @'
{
"var": [
{
"name":"ben",
"age":"24"
},
{
"name":"chris",
"age":"35"
}
]
}
'@ | ConvertFrom-Json
$json.var.where{$_.name -eq "ben"} | ConvertTo-Json
You could do the following if you want the object list formatted output rather than the JSON format.
$json.var.where{$_.name -eq "ben"} | Format-List
Explanation:
You can pipe your formatted JSON data into ConvertFrom-Json
to create a PSCustomObject
. Then you can conditionally query against the property values. Where()
method is a good option here. Finally, you can pipe back out to ConvertTo-Json
to return the output in the original JSON format. Keep in mind that the output will include the surrounding {}
.
Upvotes: 2