I want to parse JSON in PowerShell but I can't use the new v3 functions that are available in PowerShell. My first thought was to load the JSON.Net assembly and use that to parse the JSON string but it doesn't work as I expect it to.
I have this JSON:
$json = "{""Name"": ""Apple"",
""Price"": 3.99,
""Sizes"": [
""Small"",
""Medium"",
""Large""]}"
I load the JSON.NET assembly with this code:
[Reflection.Assembly]::LoadFile("$currentPath\Newtonsoft.Json.dll”)
And tries to parse it with
$result = [Newtonsoft.Json.JsonConvert]::DeserializeObject($json)
Now I expect that $result["Name"]
is Apple
but I get nothing there. Any ideas?
The code ´$result.ContainsKey("Name")returns
Truebut
$result.GetValue("Name")returns
null`.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With