Use Powershell variable in JSON

2.1k Views Asked by At

I am trying to pass a parameter through a function in powershell but it is not working

Code

function test($test1, $test2)
{
 $details = @"
{ "updateDetails": [
    {
        "customer": "John",
        "rank": $test1
    },
    {
        "school": "western",
        "address": $test2
    }
    ]
}
"@
return $details
}
test 0 florida

Current issue

{ "updateDetails": [
    {
        "customer": "John",
        "rank": 
    },
    {
        "school": "western",
        "address": florida
    }
    ]
}

I tried running test but the value 0 is not filled in the details json, florida is filled in correctly. How can I replace the two values. Also how can florida be in string

2

There are 2 best solutions below

0
On BEST ANSWER

0 fills in for me, but florida doesn't have quotes, which is invalid JSON. To make life a little easier, instead building a here-string, consider building an object and converting it to JSON with the built-in cmdlet ConvertTo-Json.

In this example I'll show you how to do it using a hashtable

function test($test1, $test2)
{
 $details = @{ 
 "updateDetails"= 
 @(
    @{
        "customer" = "John"
        "rank" = $test1
    },
    @{
        "school" = "western"
        "address" = $test2
    }
    )
}

return $details | ConvertTo-Json
}

test 0 florida

output

{
    "updateDetails":  [
                          {
                              "customer":  "John",
                              "rank":  0
                          },
                          {
                              "school":  "western",
                              "address":  "florida"
                          }
                      ]
}
0
On

Your code is perfectly fine. I ran your example and it worked as expected. Maybe you missed updating the function. Close the shell and then try again.

To include "florida" as string you could simply add quotes around the variable "$test2", or even safer: Use ConvertTo-Json to output a properly quoted and escaped JSON string:

function test {
    param ([int]$rank, [string]$address)
    return @"
    { "updateDetails": [
        {
            "customer": "John",
            "rank": $rank
        },
        {
            "school": "western",
            "address": $(ConvertTo-Json $address)
        }
        ]
    }
"@
}
test 0 florida