简体   繁体   English

在 JSON 中使用 Powershell 变量

[英]Use Powershell variable in JSON

I am trying to pass a parameter through a function in powershell but it is not working我正在尝试通过 powershell 中的 function 传递参数,但它不起作用

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.我尝试运行测试,但值 0 未填写在详细信息 json 中,佛罗里达州填写正确。 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.也许您错过了更新 function。关闭 shell,然后重试。

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:要将"florida"作为字符串包含在内,您可以简单地在变量"$test2"周围添加引号,或者更安全:使用ConvertTo-Json到 output 正确引用和转义的 JSON 字符串:

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 . 0 为我填写,但佛罗里达州没有引号,这是无效的 JSON。为了使生活更轻松,而不是构建此处字符串,请考虑构建 object 并使用内置 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 output

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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