Ronnie Kapoor
Ronnie Kapoor

Reputation: 133

how to convert array of string in json to array of strings in powershell?

I have below json

{
  "abc": [
    { "def": [ "", "" ] },
    { "ghi": [ "", "" ] },
    { "xyz" : ["\\[dbo\\].\\[abc1\\]", "\\[dbo\\].\\[def1\\]"] }
  ]
}

i want to read this json and convert string of xyz element to string array in powershell using below code but its not working.

$json = Get-Content "path to json file" | Out-String
$json = $json | ConvertFrom-Json
GetArrayFromJson -json $json
$global:array
Function GetArrayFromJson(){

Param(
    $json       
)

$global:array= ''
     $global:array

    $global:array=  $json.abc.xyz
     $global:array
}

Upvotes: 0

Views: 3855

Answers (1)

Olaf
Olaf

Reputation: 5252

That does not fit into a comment ... assumed I have a json string like this:

$rawjson = @'
{
  "abc": [
    { "def": [ "", "" ] },
    { "ghi": [ "", "" ] },
    { "xyz" : ["\\[dbo\\].\\[abc1\\]", "\\[dbo\\].\\[def1\\]"] }
  ]
}
'@ 

and I convert it to a Powershell object like this:

$json = ConvertFrom-Json -InputObject $rawjson

I can access the "xyz" property like this:

$json.abc.xyz

When I create a proper function with a single param block! ;-) like this:

Function GetArrayFromJson{
    Param(
        $json       
    )
    $json.abc.xyz
}
GetArrayFromJson $json

and run it I get both time the same output:

\[dbo\].\[abc1\]
\[dbo\].\[def1\]

Upvotes: 2

Related Questions