How do I use Json.NET to parse json in PowerShell?

Ok, so here is how I did it so it works down to at least PowerShell v2 on Windows 2008.

First, load the Json.NET assembly for the version you would like to use, I took the .NET 3.5 version:

[Reflection.Assembly]::LoadFile("Newtonsoft.Json.dll")

I had the JSON in a file since it was used in a deployment configuration I wrote, so I needed to read the file and then parse the json

$json = (Get-Content $FileName | Out-String) # read file
$config = [Newtonsoft.Json.Linq.JObject]::Parse($json) # parse string

Now to get values from the config you need to to use the Item method which seems defined by PowerShell on hashtables/dictionaries. So to get an item that is a simple string you would write:

Write-Host $config.Item("SomeStringKeyInJson").ToString()

If you had an array of things you would need to do something like

$config.Item("SomeKeyToAnArray") | ForEach-Object { Write-Host $_.Item("SomeKeyInArrayItem").ToString() }

To access nested items you write

$config.Item("SomeItem").Item("NestedItem")

That's how I solved parsing JSON with Json.NET in PowerShell.


If you get here and are using Powershell 5.0, it's available in the powershell gallery

Install-Module Newtonsoft.Json
Import-Module Newtonsoft.Json

$json = '{"test":1}'
[Newtonsoft.Json.Linq.JObject]::Parse($json)

maybe this is what you're after :

http://poshcode.org/2930

    function Convert-JsonToXml {
PARAM([Parameter(ValueFromPipeline=$true)][string[]]$json)
BEGIN { 
   $mStream = New-Object System.IO.MemoryStream 
}
PROCESS {
   $json | Write-Stream -Stream $mStream
}
END {
   $mStream.Position = 0
   try
   {
      $jsonReader = [System.Runtime.Serialization.Json.JsonReaderWriterFactory]::CreateJsonReader($mStream,[System.Xml.XmlDictionaryReaderQuotas]::Max)
      $xml = New-Object Xml.XmlDocument
      $xml.Load($jsonReader)
      $xml
   }
   finally
   {
      $jsonReader.Close()
      $mStream.Dispose()
   }
}
}

function Write-Stream {
PARAM(
   [Parameter(Position=0)]$stream,
   [Parameter(ValueFromPipeline=$true)]$string
)
PROCESS {
  $bytes = $utf8.GetBytes($string)
  $stream.Write( $bytes, 0, $bytes.Length )
}  
}



$json = '{
    "Name": "Apple",
    "Expiry": 1230422400000,
    "Price": 3.99,
    "Sizes": [
        "Small",
        "Medium",
        "Large"
    ]
}'

Add-Type -AssemblyName System.ServiceModel.Web, System.Runtime.Serialization
$utf8 = [System.Text.Encoding]::UTF8                 
(convert-jsonToXml $json).innerXML

Output :

<root type="object"><Name type="string">Apple</Name><Expiry type="number">1230422
400000</Expiry><Price type="number">3.99</Price><Sizes type="array"><item type="s
tring">Small</item><item type="string">Medium</item><item type="string">Large</it
em></Sizes></root>

If you want the name node :

$j=(convert-jsonToXml $json)
$j.SelectNodes("/root/Name")

or

$j |Select-Xml -XPath "/root/Name" |select -ExpandProperty node