Get values from variable contents using PowerShell for code parsing
I have parsed the content of an API call to a variable $a.(Content below) and I would like to only parse out the list of packages which are under "dependencies". Is there are way to filter for only the dependencies using powershell?.
{
"name": "1package",
"version": "1.0.0",
"lockfileVersion": 1,
"requires": true,
"dependencies": {
"@babel/runtime": {
"version": "7",
"resolved": "https://registry.npmjs.org",
"integrity": "***",
"requires": {
"regenerator-runtime": "^0.13.4"
}
},
"@cloud": {
"version": "2",
"resolved": "https://registry.npmjs.org/",
"integrity": "***"
},
"@cloudnative/health-connect": {
"version": "2",
"resolved": "https://registry.npmjs.org/@***.tgz",
"integrity": "***",
"requires": {
"@cloudnative/health": "^2.1.1"
}
},
So I just want to parse out a list having
babel/runtime version 7
cloud version 2
cloudnative/health-connect version 2
By accessing the PSObject.Properties
of each object we can get the dependency "Name" and the desired values of the properties "Version" and "Resolved". Using a calculated property with Select-Object
we can construct a new object.
Note, this code assumes you have already used ConvertFrom-Json
over your Json string and, the object is stored in the $json
variable.
$json.dependencies.PSObject.Properties | Select-Object Name,
@{
Name = 'Version'
Expression = { $_.Value.Version }
}, @{
Name = 'Resolved'
Expression = { $_.Value.Resolved }
}
Output
Name Version Resolved
---- ------- --------
@babel/runtime 7 https://registry.npmjs.org
@cloud 2 https://registry.npmjs.org/
@cloudnative/health-connect 2 https://registry.npmjs.org/@***.tgz