I am trying to get into Powershell and am trying to convert a simple JSON file to table format.
The json-file looks like this:
{ "Members" : [
{ "Id" : 1,
"Details" : [ { "FirstName" : "Adam" }, { "LastName" : "Ant" } ] },
{ "Id" : 2,
"Details" : [ { "FirstName" : "Ben" }, { "LastName" : "Boggs" } ] },
{ "Id" : 3,
"Details" : [ { "FirstName" : "Carl"} , { "LastName" : "Cox" } ] }
]
}
Powershell expression:
$jString.Members.details | Select-Object -Property Id, FirstName, LastName
output so far (best I got).. id missing
Id FirstName LastName
-- --------- --------
Adam Ant
Ben Boggs
Carl Cox
How would I accomplish that?
Any help appreciated
Yes, ImportJSON is a really easy tool to use for taking information from JSON and putting it into a table or spreadsheet. Including if you want to parse your JSON directly from Google Sheets!
We can use the pipeline command ConvertFrom−JSON to convert the JSON file to the custom table format and with the −AsHashtable parameter to convert the custom object to the hashtable.
PowerShell makes it easy to modify JSON by converting JSON to a PSCustomObject. The object can then be modified easily like any other object. The object can then be exported back out using ConvertTo-Json. Now if we're on a computer without PowerShell 7.1 we try to run the same command in PowerShell 5.1 but it fails!
To convert the JSON file to the CSV file using PowerShell, we need to use the ConvertTo-CSV command as a pipeline. For example, we have a JSON file called PatchingServer. JSON stored at C:\temp and its content is as below.
JSON is not my strength but if you look at the data structure ID is not on the same level as first and last name which is nested in details. I put the data in a here-string for testing.
$json = @"
{ "Members" : [
{ "Id" : 1,
"Details" : [ { "FirstName" : "Adam" }, { "LastName" : "Ant" } ] },
{ "Id" : 2,
"Details" : [ { "FirstName" : "Ben" }, { "LastName" : "Boggs" } ] },
{ "Id" : 3,
"Details" : [ { "FirstName" : "Carl"} , { "LastName" : "Cox" } ] }
]
}
"@ | ConvertFrom-Json | Select-Object -Expand Members
$json | Select ID,@{Name="FirstName";E={$_.Details | Select -Expand FirstName}},@{Name="LastName";E={$_.Details | Select -Expand LastName}}
I use calculated properties to get those "nested" details associated to each ID
Which gets me the following results.
Id FirstName LastName
-- --------- --------
1 Adam Ant
2 Ben Boggs
3 Carl Cox
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With