I have a variable $result containing JSON data.
Write-Host $result ## would give this result:
{
"format": {
"filename": ".\C0001.MP4",
"nb_streams": 3,
"nb_programs": 0,
"format_name": "mov,mp4,m4a,3gp,3g2,mj2",
"format_long_name": "QuickTime / MOV",
"start_time": "0.000000",
"duration": "55.680000",
"size": "360720447",
"bit_rate": "51827650",
"probe_score": 100,
"tags": {
"major_brand": "XAVC",
"minor_version": "16785407",
"compatible_brands": "XAVCmp42iso2",
"creation_time": "2023-07-28T07:10:05.000000Z"
}
}
}
How do I retrieve the value of "major_brand" and put it into a variable?
2
Answers
Use the aptly named
ConvertFrom-Json
cmdlet to convert your JSON into an object hierarchy you can interrogate programmatically:Now we can do:
The ConvertFrom-Json PowerShell cmdlet can be used to achieve what you are looking for. In the code below, I’ve copy-pasted your JSON data and assigned it to the PS variable $jsonString.
Then, using the ConvertFrom-Json cmdlet, I’ve converted the JSON string into a usable PS object, $object.
I’ve given you an example at the bottom for assigning major_brand to variable $MajorBrand and then writing that out to the host.
Because of the nested structure of your provided PowerShell object, to obtain the major_brand property, we have to navigate first through parent properties tags and format. This leaves us with $object.format.tags.major_brand.
ConvertFrom-Json cmdlet info from Microsoft: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/convertfrom-json?view=powershell-7.4