簡體   English   中英

在 JSON 中使用 Powershell 變量

[英]Use Powershell variable in JSON

我正在嘗試通過 powershell 中的 function 傳遞參數,但它不起作用

代碼

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

目前的問題

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

我嘗試運行測試,但值 0 未填寫在詳細信息 json 中,佛羅里達州填寫正確。 我怎樣才能替換這兩個值。 還有佛羅里達怎么能成串

您的代碼非常好。 我運行了您的示例,它按預期工作。 也許您錯過了更新 function。關閉 shell,然后重試。

要將"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 為我填寫,但佛羅里達州沒有引號,這是無效的 JSON。為了使生活更輕松,而不是構建此處字符串,請考慮構建 object 並使用內置 cmdlet ConvertTo-將其轉換為 JSON- 傑森

在這個例子中,我將向您展示如何使用哈希表來做到這一點

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM