Mike Mike - 2 months ago 19
JSON Question

PowerShell -- Accessing a JArray inside a JObject

I have a Json object

{
"ProjectDirectory": "C:\\Main",
"SiteName": "RemoteOrder",
"ParentPath": "/Areas//Views",
"VirtualDirectories": [
{
"Name": "Alerts",
"Path": "\\Areas\\RemoteOrder\\Views\\Alerts"
},
{
"Name": "Analytics",
"Path": "\\Areas\\RemoteOrder\\Views\\Analytics"
},
{
"Name": "Auth",
"Path": "\\Areas\\RemoteOrder\\Views\\Auth"
}
]
}


that I created by

$config = [Newtonsoft.Json.Linq.JObject]::Parse($file)


I can access things like

$config["ProjectDirectory"]
$config["VirtualDirectories"]


But I can not get to the element inside the VirtualDirectories JArray

I confirmed

$config["VirtualDirectories"][0].GetType() // JObject
$config["VirtualDirectories"].GetType() // JArray
$config // JObject


I have tried

$config["VirtualDirectories"][0]["Name"]
$config["VirtualDirectories"][0]["Path"]
$config["VirtualDirectories"][0][0]
$config["VirtualDirectories"][0].GetValue("Name")


When I try

$config["VirtualDirectories"][0].ToString()


I get

{
"Name": "Alerts",
"Path": "\\Areas\\RemoteOrder\\Views\\Alerts"
}


What I am really trying to do is access it a loop but again I can not seem to access the JObject Elements

Answer Source

You are close. $config["VirtualDirectories"][0]["Name"] will give you a JValue containing the text. You just need to use the Value property from there to get the actual string. Here is how you would do it in a ForEach loop:

$config = [Newtonsoft.Json.Linq.JObject]::Parse($file)

ForEach ($dir in $config["VirtualDirectories"])
{
    $name = $dir["Name"].Value
    $path = $dir["Path"].Value
    ...
}