简体   繁体   中英

Use Powershell variable in JSON

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

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

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"
                          }
                      ]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM