如何在已解析的 JSON 数组中添加对象?
How to add an object in array on parsed JSON?
我有这个文件。json:
{
"topologyTypes": {
"stations": {
"instances": [
{
"@name": "value1",
"@address": "value2"
},
{
"@name": "value3",
"@address": "value4"
}
]
}
},
"agg": {},
"inter": {}
}
我想使用 PowerShell
在 topologyType.stations.instances 中添加这样的对象
{
"@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": {}
}
将新内容定义为 PowerShell 自定义对象:
$jsonContent = [PSCustomObject]@{
'@name' = 'value4'
'@adress' = 'value5'
}
将其附加到导入的 JSON 数据的 instances
子结构中:
$jsonFile.topologyTypes.stations.instances += $jsonContent
然后将数据转换回 JSON 字符串:
$jsonFile | ConvertTo-Json -Depth 4
请注意 ConvertTo-Json
插入了很多意图 space。如果你想要你发布的格式,你需要自己做一些漂亮的打印。 this 之类的内容可能会有所帮助。
我有这个文件。json:
{
"topologyTypes": {
"stations": {
"instances": [
{
"@name": "value1",
"@address": "value2"
},
{
"@name": "value3",
"@address": "value4"
}
]
}
},
"agg": {},
"inter": {}
}
我想使用 PowerShell
在 topologyType.stations.instances 中添加这样的对象{
"@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": {}
}
将新内容定义为 PowerShell 自定义对象:
$jsonContent = [PSCustomObject]@{
'@name' = 'value4'
'@adress' = 'value5'
}
将其附加到导入的 JSON 数据的 instances
子结构中:
$jsonFile.topologyTypes.stations.instances += $jsonContent
然后将数据转换回 JSON 字符串:
$jsonFile | ConvertTo-Json -Depth 4
请注意 ConvertTo-Json
插入了很多意图 space。如果你想要你发布的格式,你需要自己做一些漂亮的打印。 this 之类的内容可能会有所帮助。