Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell - JSON file to table

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

like image 288
user3873139 Avatar asked Jul 14 '15 19:07

user3873139


People also ask

Can we convert JSON to table?

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!

How to Convert a JSON file to hashtable in PowerShell?

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.

How do I parse JSON data in PowerShell?

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!

How to Convert JSON into CSV using PowerShell?

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.


1 Answers

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   
like image 145
Matt Avatar answered Oct 12 '22 23:10

Matt