Question:
I am trying to create a table from a JSON file I am receiving from a RESTful API.
When I print the property of the json object I get an output like this:
1 2 3 4 5 6 |
PS> Write-Output JSON.Object Object1 : @{key1=property; key2=property; key3=property; key4=property} Object2 : @{key1=property; key2=property; key3=property; key4=property} Object3 : @{key1=property; key2=property; key3=property; key4=property} Object4 : @{key1=property; key2=property; key3=property; key4=property} |
The output I would like to see is this:
1 2 3 4 5 |
Name key1 key2 key3 key4 ----- ---- ---- ---- ---- Object1 property property property property Object2 property property property property Object3 property property property property |
In addition, is it possible to avoid displaying a specific key and it’s properties?
Example:
1 2 3 4 5 |
Name key1 key2 key4 # ← Not displaying key3 ----- ---- ---- ---- Object1 property property property Object2 property property property Object3 property property property |
Answer:
You need to add the parent keyname as a property Name
to the nested objects:
1 2 3 4 5 6 |
$json.Object | ForEach-Object { foreach ($p in $_.PSObject.Properties) { $p.Value | Select-Object @{n='Name';e={$p.Name}},* } } |
Note that PowerShell will render the output in list form by default, since your objects have more than 4 properties. Pipe it through Format-List -AutoSize
to get tabular output.