我是PowerShell的新手,正在尝试瘦身.我想解析在Powershell中具有对其他JSON对象的引用的JSON对象.
I am new to powershell and trying to lean. I want to have parse JSON objects that have references to other JSON object in Powershell.
在我的JSON文件中,我定义了一个默认对象,其值键为W.我希望能够在其他JSON对象中使用此$ default.value引用,以避免在多个地方定义值.
In my JSON file I define a default object with a value key=W. I want to be able to use this $default.value reference in other JSON objects, to avoid having multiple places where a values are defined.
当我提取键$ driveletter = $ json.target.driveletter时,我无法算出能够将字符串$ default.value转换为W值的语法
I cannot work out the syntax to be able to turn the string $default.value to the W value when I extract the key $driveletter=$json.target.driveletter
在Powershell中有可能吗?
Is this possible in powershell?
谢谢
斯图尔特
Example.JSON
Example.JSON
{default: {value: "W"},target: {driveletter: "'"$default.value"}}doit-example.ps1
doit-example.ps1
$json = (Get-Content "example.json" -Raw) | ConvertFrom-Json # #Create object called default that I can reference from other objects # $default=$json.default $default.value # # How do I use the string in the json.target.driveletter # $json.target.driveletter $driveletter=$json.target.driveletter $driveletter $json.target.driveletter.GetType()输出
.\doit-example.ps1 W $default.value $default.value IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True String System.Object推荐答案
将您的json文件模板更改为可以更正确地解析为powershell-string模板的字符串模板:
Change your json-file template to a string template that could be parsed more properly as a powershell-string template:
示例(test.json):
Example (test.json):
{default: {value: "W"},target: {driveletter: "$($default.value)"}}然后您可以执行以下操作:
Then you could do the following:
$file = "C:\tmp\test.json"; # Read the "template json with defaults" $json = (Get-Content $file -Raw) | ConvertFrom-Json # Read the raw content into a variable for expansion $rawContent = (Get-Content $file -Raw); # Set the default object (to be able to expand string) $default = $json.default; # Your new json $newJson = ($ExecutionContext.InvokeCommand.ExpandString($rawContent)) | ConvertFrom-Json这将用您设置的任何默认对象替换"json"模板的内容.请注意,使用expandstring时,您需要在会话中设置默认".
This will replace the content of your "json" template with whatever default object you set. Note that you need to have the "default" set in your session when using expandstring.
此示例的输出将产生:
default target ------- ------ @{value=W} @{driveletter=W}您可以访问$ newJson.targer.driveletter的属性(它将设置为默认值)
You could access your propery for $newJson.targer.driveletter (and it will be set to your default)
要打印目标驱动器字母(其值已替换为默认值),请使用:
To print your target driveletter (with the value(s) replaced from default) use:
$newJson.target.driveletter更多推荐
JSON和对其他JSON对象的引用
发布评论