我有这个文件.json:
{
"topologyTypes": {
"stations": {
"instances": [
{
"@name": "value1",
"@address": "value2"
},
{
"@name": "value3",
"@address": "value4"
}
]
}
},
"agg": {},
"inter": {}
}
我想在topologyType.stations.instances中使用PowerShell
添加这样的对象{
"@name": "value4",
"@adress": "value5"
}
所以我在PowerShell中尝试了以下代码,但它不起作用:
$path = "./data.json"
$jsonFile = Get-Content $path -Raw | ConvertFrom-Json
$jsonContent = @"
{
"@name": "value4",
"@adress": "value5"
}
"@
$jsonFile.topologyTypes.stations.instances |
Add-Content -Value (ConvertFrom-Json $jsonContent)
我想要的输出是这样的:
{
"topologyTypes": {
"stations": {
"instances": [
{
"@name": "value1",
"@address": "value2"
},
{
"@name": "value3",
"@address": "value4"
},
{
"@name": "value4",
"@address": "value5"
}
]
}
},
"agg": {},
"inter": {}
}
答案 0 :(得分:2)
将新内容定义为PowerShell自定义对象:
$jsonContent = [PSCustomObject]@{
'@name' = 'value4'
'@adress' = 'value5'
}
将其附加到导入的JSON数据的instances
子结构中:
$jsonFile.topologyTypes.stations.instances += $jsonContent
然后将数据转换回JSON字符串:
$jsonFile | ConvertTo-Json -Depth 4
请注意,ConvertTo-Json
会插入大量意图空间。如果你想要你发布的格式,你需要自己做一些漂亮的打印。像this这样的东西可能会有所帮助。