0

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
}
5
  • What do you mean with "its not working"? You know that you have to create a function before you can us it, don't you?
    – Olaf
    Commented Mar 25, 2018 at 11:36
  • yes, here i mistakenly wrote it above the function.. but the function is available ..what i mean say from not working that i want the output to be equal to same if i declare the variable as $global:array = "\[dbo\].\[abc1\]", "\[dbo\].\[def1\]". did you get it? Commented Mar 25, 2018 at 11:38
  • in simple words, i want to read an element of json which has string array and convert it into string array in powershell Commented Mar 25, 2018 at 11:39
  • Hmmm ... but if you use ConvertFrom-Jsonit is already Powershell. You can output it with $json.abc.xyz
    – Olaf
    Commented Mar 25, 2018 at 11:41
  • right , that is what is done.. please read . the problem is the output of this is not expected and equal to the situation if i declare the variable to be $global:array = "[dbo].[abc1]", "[dbo].[def1]". shouldn't it be ? Commented Mar 25, 2018 at 11:46

1 Answer 1

2

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\]

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.