gpt4 book ai didi

json - Powershell - 将内容注入(inject)到json文件中

转载 作者:行者123 更新时间:2023-12-03 07:31:00 24 4
gpt4 key购买 nike

我必须将一些数据注入(inject)到 json 文件中。我正在使用 powershell 代码,如下所示。这只是我的脚本的摘录。变量 $MwTagsSelected 是 pscustom 对象的数组,如下所示。$MwTagsSelected 具有三个属性:TagIndexTagNameTagValue。我通过下面给出的 foreach 循环传递该对象,结果我得到对象数组 $FilteredObjectArray。下面介绍了这两个对象数组。我想使用代码 $jsoncontent.Resources.MaintenanceWindowTarget.Properties.Targets = $FilteredObjectArray

$FilteredObjectArray 注入(inject) json 文件

$MwTagsSelected:

enter image description here

$FilteredObjectArray

enter image description here

我的powershell代码:

# get JSON file content
$filename = "inputfile.json"
$content = Get-Content -Path .\$filename
$jsoncontent = $content | ConvertFrom-Json
# JSON file input preparation
$Keys = ($MwTagsSelected | Select-Object -Property TagName -unique).TagName
$FilteredObjectArray = @()
$NotAllowedSelections = @()
$Value = @()

foreach ($Key in $Keys) {
$Value += $MwTagsSelected | Where-Object -FilterScript {$_.TagName -eq $Key}
$FilteredObject = [pscustomobject][ordered] @{
Key = "tag:$Key"
Values = $Value.TagValue
}

if ($Value.Count -gt 5) {
$NotAllowedSelections += $Key
}
$FilteredObjectArray += $FilteredObject
$Value = @()
}

$jsoncontent.Resources.MaintenanceWindowTarget.Properties.Targets = $FilteredObjectArray

$jsoncontent |
ConvertTo-Json -Depth 15 |
Set-Content .\test.json

作为该脚本的输出,我得到了 json 文件,但 json 结构与预期不符,下面是我的输出 test.json 文件中的摘录。

"Targets": [
{
"Key": "tag:win",
"Values": [
"01",
"02"
]
},
{
"Key": "tag:ein",
"Values": "03"
}
],

输出 test.json 文件应如下所示:

"Targets": [
{
"Key": "tag:win",
"Values": [
"01",
"02"
]
},
{
"Key": "tag:ein",
"Values": [
"03"
]
}
],

最佳答案

如果你想确保值是一个数组,你可以用@()包围它

    $FilteredObject = [pscustomobject][ordered] @{
Key = "tag:$Key"
Values = @($Value.TagValue)
}

查看这些简化的示例

示例数据

$ht = @{
Tag="win"
TagValue=1,2
},
@{
Tag="ein"
TagValue=3
}

没有@()

$ht.GetEnumerator() | % {
[PSCustomObject]@{
Key = $_.tag
Values = $_.tagvalue
}
} | ConvertTo-Json

[
{
"Key": "win",
"Values": [
1,
2
]
},
{
"Key": "ein",
"Values": 3
}
]

使用@()

$ht.GetEnumerator() | % {
[PSCustomObject]@{
Key = $_.tag
Values = @($_.tagvalue)
}
} | ConvertTo-Json

[
{
"Key": "win",
"Values": [
1,
2
]
},
{
"Key": "ein",
"Values": [
3
]
}
]

另外,您不需要将 [Ordered][PSCustomObject] - 默认情况下它将保留顺序。

关于json - Powershell - 将内容注入(inject)到json文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64504446/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com