我想通过在json模板文件中替换环境变量的值来创建json文件



我的一个要求是-使用windows,不要使用任何aws-cli或windows中没有的工具例如,我有一个json文件test.json,内容如下:

"My number is $myvar"

我把这个读进了一个powershell变量中,如下所示:

$myobj=(get-content .test.json | convertfrom-json)
$myvar=1

从这里开始,我想用这个$myobj做点什么,这将使我能够获得以下输出:

$myobj | tee json_with_values_from_environment.json
My number is 1

我在iex上取得了一些有限的成功,但不确定它是否能用于这个例子

您可以使用$ExecutionContext.InvokeCommand.ExpandString()

$myobj = '{test: "My number is $myvar"}' | ConvertFrom-Json
$myvar = 1
$ExecutionContext.InvokeCommand.ExpandString($myobj.test)

输出

My number is 1

以下是使用Parser查找所有VariableExpressionAst并用会话中的值替换它们的一种方法。

给定以下test.json:

{
"test1": "My number is $myvar",
"test2": {
"somevalue": "$env:myothervar",
"someothervalue": "$anothervar !!"
}
}

我们希望找到$myvar$myothervar$anothervar,并将其替换为当前会话中定义的相应值,因此代码如下所示(请注意,我们在将Json字符串转换为对象之前进行替换,这种方式要容易得多(:

using namespace System.Management.Automation.Language
$isCore7 = $PSVersionTable.PSVersion -ge '7.2'
# Define the variables here
$myvar = 10
$env:myothervar = 'hello'
$anothervar = 'world'
# Read the Json
$json = Get-Content .test.json -Raw
# Now parse it
$ast = [Parser]::ParseInput($json, [ref] $null, [ref] $null)
# Find all variables in it,  and enumerate them
$ast.FindAll({ $args[0] -is [VariableExpressionAst] }, $true) |
Sort-Object { $_.Extent.Text } -Unique | ForEach-Object {
# now replace the text with the actual value
if($isCore7) {
# in PowerShell Core is very easy
$json = $json.Replace($_.Extent.Text, $_.SafeGetValue($true))
return
}
# in Windows PowerShell not so much
$varText = $_.Extent.Text
$varPath = $_.VariablePath
# find the value of the var (here we use the path)
$value = $ExecutionContext.SessionState.PSVariable.GetValue($varPath.UserPath)
if($varPath.IsDriveQualified) {
$value = $ExecutionContext.SessionState.InvokeProvider.Item.Get($varPath.UserPath).Value
}
# now replace the text with the actual value
$json = $json.Replace($varText, $value)
}
# now we can safely convert the string to an object
$json | ConvertFrom-Json

如果我们将其转换回Json以查看结果:

{
"test1": "My number is 10",
"test2": {
"somevalue": "hello",
"someothervalue": "world !!"
}
}

最新更新