Manipulating JSon with PowerShell

A few tips about working with JSon in PowerShell.

Reading JSon from a file

$file = Get-Content c:\tmp\file.json

Converting from text to JSon in PowerShell v3 or v4

$json = $file | ConvertFrom-JSON

Converting from text to JSon in PowerShell v2

Loading the assembly System.Web.Extensions will help in PowerShell v2. This assembly is however present only in .NET 3.5 and higher, so if you don’t have that installed, this solution is not appropriate.

[System.Reflection.Assembly]::LoadWithPartialName("System.Web.Extensions")
$serializer = New-Object System.Web.Script.Serialization.JavaScriptSerializer
$json = $serializer.DeserializeObject($file)

Appending JSon objects

Given that $obj1JSon and $obj2JSon is two valid JSon objects.

$newJson = $obj1JSon + $obj2JSon

Serialize a JSon file to disk in PowerShell v3 or v4

$newJsonFile = $json | ConvertFrom-Json
Set-Content c:\tmp\new.json $newJsonFile

Serialize a JSon file to disk in PowerShell v2

Using the previous v2 trick with methods from System.Web.Extensions loaded.

[System.Reflection.Assembly]::LoadWithPartialName("System.Web.Extensions")
$serializer = New-Object System.Web.Script.Serialization.JavaScriptSerializer
$newJsonFile = $serializer.Serialize($newJSon)
Set-Content c:\tmp\TOwork\created.json $newJsonFile

Checking the PowerShell Version

Not sure what version of PowerShell you are running? Run the command below to find out. The Major Version is the indicator telling you what version that is installed.

$PSVersionTable.PSVersion
PowerShell – Working with JSon
Tagged on:

2 thoughts on “PowerShell – Working with JSon

  • April 5, 2016 at 17:12
    Permalink

    You need to add the -raw switch to this line:
    $file = Get-Content c:tmpfile.json -raw

    Reply
    • April 8, 2016 at 00:45
      Permalink

      What version of PowerShell are you running?

      I only got access to v5 right now and in that I’ve found no need of using -raw, the conversion to json have worked for me fine without it.

      Thanks for the feedback 🙂

      Reply

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.