Skip to content

Instantly share code, notes, and snippets.

@matthewoestreich
Last active November 3, 2019 00:52
Show Gist options
  • Save matthewoestreich/5be35ed5bf816cc5d61304d785f5dcc7 to your computer and use it in GitHub Desktop.
Save matthewoestreich/5be35ed5bf816cc5d61304d785f5dcc7 to your computer and use it in GitHub Desktop.
Add-JsonToTreeView Source Code For Demo
function Show-jsonTreeView_psf {
#----------------------------------------------
#region Import the Assemblies
#----------------------------------------------
[void][reflection.assembly]::Load('System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a')
[void][reflection.assembly]::Load('System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089')
#endregion Import Assemblies
#----------------------------------------------
#region Generated Form Objects
#----------------------------------------------
[System.Windows.Forms.Application]::EnableVisualStyles()
$formAddJsonToTreeviewDem = New-Object 'System.Windows.Forms.Form'
$buttonLoadJSONString = New-Object 'System.Windows.Forms.Button'
$buttonLoadJSONFromAPI = New-Object 'System.Windows.Forms.Button'
$treeview1 = New-Object 'System.Windows.Forms.TreeView'
$InitialFormWindowState = New-Object 'System.Windows.Forms.FormWindowState'
#endregion Generated Form Objects
#----------------------------------------------
# User Generated Script
#----------------------------------------------
function Add-JsonToTreeview {
########################################################################################
# #
# The MIT License #
# #
# Copyright (c) 2019 Matt Oestreich. http://mattoestreich.com #
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy #
# of this software and associated documentation files (the "Software"), to deal #
# in the Software without restriction, including without limitation the rights #
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell #
# copies of the Software, and to permit persons to whom the Software is #
# furnished to do so, subject to the following conditions: #
# #
# The above copyright notice, accreditation to Matt Oestreich, and this permission #
# notice shall be included in all copies or substantial portions of the Software. #
# #
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN #
# THE SOFTWARE. #
# #
########################################################################################
<#
.SYNOPSIS
Add JSON to TreeView
.DESCRIPTION
Add JSON to TreeView (System.Windows.Forms.TreeView) Component
.PARAMETER Json
JSON data (`-Json` can be a `[String]` or converted JSON string (aka `[PsCustomObject]`) converted using `ConvertFrom-Json`). See examples for more details.
.PARAMETER TreeView
The TreeView (System.Windows.Forms.TreeView) that you want to add JSON to
.PARAMETER ParentNode
This is here for recursion - you will most likely not need to use this Parameter
9.99 times out of 10.00 you wil not need to use this Parameter
.EXAMPLE
PS C:\> $SomeTreeView = [System.Windows.Forms.TreeView]::new()
PS C:\> $myJsonString = '{ "Root": [{ "Child1": "Value1" }, { "Child2": "Value2" }, { "Child3": "Value3" }] }'
PS C:\> $myJsonConverted = $myJsonString | ConvertFrom-Json
PS C:\> Add-JsonToTreeview -Json $myJsonConverted -TreeView $SomeTreeView
.EXAMPLE
PS C:\> $SomeTreeView = [System.Windows.Forms.TreeView]::new()
PS C:\> $myJsonString = '{ "Root": [{ "Child1": "Value1" }, { "Child2": "Value2" }, { "Child3": "Value3" }] }'
PS C:\> Add-JsonToTreeview -Json $myJsonString -TreeView $SomeTreeView
.NOTES
Matt Oestreich | http://mattoestreich.com | https://github.com/oze4
#>
param (
[Parameter(Mandatory = $true)]
$Json,
[Parameter(Mandatory = $true)]
[System.Windows.Forms.TreeView]$TreeView,
[Parameter(Mandatory = $false)]
[System.Windows.Forms.TreeNode]$ParentNode
)
begin {
function New-TreeViewNode {
<#
.DESCRIPTION
Helper function to create TreeNode objects
#>
param (
[Parameter(Mandatory = $true)]
[string]$Value
)
$NewNode = [System.Windows.Forms.TreeNode]::new($Value)
$NewNode.Name = $Value
return $NewNode
}
function Add-ObjectToTreeView {
<#
.DESCRIPTION
Helper function to add type `Object[]` to TreeView
#>
param (
[Parameter(Mandatory = $true)]
[System.Object[]]$Object,
[Parameter(Mandatory = $false)]
[System.Windows.Forms.TreeNode]$AddToNode,
[Parameter(Mandatory = $true)]
[System.Windows.Forms.TreeView]$TargetTreeView
)
$counter = 0
foreach ($objectProp in $Object) {
if ((($objectProp | Get-Member -Type NoteProperty).Count) -gt 1) {
$objectProp = "{
`"$($counter)`": $($objectProp | ConvertTo-Json)
}"
$counter++
}
Add-JsonToTreeview -Json $objectProp -ParentNode $AddToNode -TreeView $TargetTreeView
}
}
}
process {
switch ($Json.GetType().Name) {
'PsCustomObject' {
foreach ($jsonProperty in $Json.PsObject.Properties) {
$node = New-TreeViewNode -Value $jsonProperty.Name
$addTo = $TreeView
if ($ParentNode) {
$addTo = $ParentNode
}
$addTo.Nodes.Add($node)
if ($jsonProperty.GetType().Name -eq 'Object[]') {
Add-ObjectToTreeView -Object $jsonProperty -AddToNode $node -TargetTreeView $TreeView
} else {
Add-JsonToTreeview -Json $jsonProperty.Value -ParentNode $node -TreeView $TreeView
}
}
}
'Object[]' {
Add-ObjectToTreeView -Object $Json -AddToNode $ParentNode -TargetTreeView $TreeView
}
'String' {
try {
Add-JsonToTreeview -Json ($Json | ConvertFrom-Json) -ParentNode $ParentNode -TreeView $TreeView
} catch {
$addTo = $TreeView
if ($ParentNode) {
$addTo = $ParentNode
}
$addTo.Nodes.Add((New-TreeViewNode -Value $Json))
}
}
} # // switch
if ($Json -is [ValueType]) {
try {
$addTo = $TreeView
if ($ParentNode) {
$addTo = $ParentNode
}
$addTo.Nodes.Add((New-TreeViewNode -Value $Json.ToString()))
} catch {
# only here to silence errors
}
}
}
}
$buttonLoadJSONFromAPI_Click = {
try {
$url = "https://jsonplaceholder.typicode.com/todos/"
$jsonResults = Invoke-RestMethod -Method Get -Uri $url | ConvertTo-Json
$results = "{ `"API Data`": $($jsonResults) }"
Add-JsonToTreeview -Json $results -TreeView $treeview1
} catch {
Add-JsonToTreeview -Json "ERROR GETTING JSON FROM API" -TreeView $treeview1
}
}
$buttonLoadJSONString_Click={
$jsonData = '{ "Example Data": [{ "Child1": "Value1" }, { "Child2": "Value2" }, { "Child3": "Value3" }] }'
Add-JsonToTreeview -Json $jsonData -TreeView $treeview1
}
# --End User Generated Script--
#----------------------------------------------
#region Generated Events
#----------------------------------------------
$Form_StateCorrection_Load=
{
#Correct the initial state of the form to prevent the .Net maximized form issue
$formAddJsonToTreeviewDem.WindowState = $InitialFormWindowState
}
$Form_Cleanup_FormClosed=
{
#Remove all event handlers from the controls
try
{
$buttonLoadJSONString.remove_Click($buttonLoadJSONString_Click)
$buttonLoadJSONFromAPI.remove_Click($buttonLoadJSONFromAPI_Click)
$formAddJsonToTreeviewDem.remove_Load($Form_StateCorrection_Load)
$formAddJsonToTreeviewDem.remove_FormClosed($Form_Cleanup_FormClosed)
}
catch { Out-Null <# Prevent PSScriptAnalyzer warning #> }
}
#endregion Generated Events
#----------------------------------------------
#region Generated Form Code
#----------------------------------------------
$formAddJsonToTreeviewDem.SuspendLayout()
#
# formAddJsonToTreeviewDem
#
$formAddJsonToTreeviewDem.Controls.Add($buttonLoadJSONString)
$formAddJsonToTreeviewDem.Controls.Add($buttonLoadJSONFromAPI)
$formAddJsonToTreeviewDem.Controls.Add($treeview1)
$formAddJsonToTreeviewDem.AutoScaleDimensions = '6, 13'
$formAddJsonToTreeviewDem.AutoScaleMode = 'Font'
$formAddJsonToTreeviewDem.ClientSize = '440, 606'
$formAddJsonToTreeviewDem.MaximizeBox = $False
$formAddJsonToTreeviewDem.MinimizeBox = $False
$formAddJsonToTreeviewDem.Name = 'formAddJsonToTreeviewDem'
$formAddJsonToTreeviewDem.Text = 'Add-JsonToTreeview | Demo'
#
# buttonLoadJSONString
#
$buttonLoadJSONString.Location = '214, 10'
$buttonLoadJSONString.Name = 'buttonLoadJSONString'
$buttonLoadJSONString.Size = '214, 31'
$buttonLoadJSONString.TabIndex = 2
$buttonLoadJSONString.Text = 'Load JSON String'
$buttonLoadJSONString.UseCompatibleTextRendering = $True
$buttonLoadJSONString.UseVisualStyleBackColor = $True
$buttonLoadJSONString.add_Click($buttonLoadJSONString_Click)
#
# buttonLoadJSONFromAPI
#
$buttonLoadJSONFromAPI.Location = '12, 10'
$buttonLoadJSONFromAPI.Name = 'buttonLoadJSONFromAPI'
$buttonLoadJSONFromAPI.Size = '196, 31'
$buttonLoadJSONFromAPI.TabIndex = 1
$buttonLoadJSONFromAPI.Text = 'Load JSON From API'
$buttonLoadJSONFromAPI.UseCompatibleTextRendering = $True
$buttonLoadJSONFromAPI.UseVisualStyleBackColor = $True
$buttonLoadJSONFromAPI.add_Click($buttonLoadJSONFromAPI_Click)
#
# treeview1
#
$treeview1.Location = '12, 49'
$treeview1.Name = 'treeview1'
$treeview1.Size = '416, 545'
$treeview1.TabIndex = 0
$formAddJsonToTreeviewDem.ResumeLayout()
#endregion Generated Form Code
#----------------------------------------------
#Save the initial state of the form
$InitialFormWindowState = $formAddJsonToTreeviewDem.WindowState
#Init the OnLoad event to correct the initial state of the form
$formAddJsonToTreeviewDem.add_Load($Form_StateCorrection_Load)
#Clean up the control events
$formAddJsonToTreeviewDem.add_FormClosed($Form_Cleanup_FormClosed)
#Show the Form
return $formAddJsonToTreeviewDem.ShowDialog()
} #End Function
#Call the form
Show-jsonTreeView_psf | Out-Null
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment