Powershell and JSON – Part 1

Get the List of JSON PowerShell commandlet from Get-Command

Get-Command *JSON*

Reading JSON Document

$file="G:\Dummy_Data\world_bank\test1.json" 

(Get-Content  -Path $file -Raw)| ConvertFrom-Json

Pass JSON as InputObject to ConvertFrom-JSON commandlet

$jdata=Get-Content  -Path $file -Raw
$data=ConvertFrom-Json -InputObject $jdata

$data 

Now Get the members, the properties, and methods, of objects.

$jdata=Get-Content  -Path $file -Raw
$data=ConvertFrom-Json -InputObject $jdata

$data |Get-Member

Retrieve Property Value

$jdata=Get-Content  -Path $file -Raw
$data=ConvertFrom-Json -InputObject $jdata

#$data |Get-Member

$data.id

Retrieve Array

--Data Example
majorsector_percent      : {@{Name=Transportation; Percent=100}}
<#####################################################################>

[string] $file='G:\Dummy_Data\world_bank\test1.json'

If( Test-Path -Path $file)
{
   
   $data=(Get-Content  -Path $file -Raw)| ConvertFrom-Json 
    
    $data.majorsector_percent
    
       foreach ($object in $data )
        {
                     
           $object.majorsector_percent
        }
       
}

Retrieve Array Value using -ExpandProperty

[string] $file='G:\Dummy_Data\world_bank\test1.json'

If( Test-Path -Path $file)
{
   
   $data=(Get-Content  -Path $file -Raw)| ConvertFrom-Json 
    
    $data.majorsector_percent
    
       foreach ($object in $data )
        {
         $object|Where-Object {$_.id -eq $object.id}|select -ExpandProperty majorsector_percent | select Name,Percent
        }      
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *