如何在解析的 JSON 数组中添加对象?

J. *_*Sam 1 arrays powershell json object addition

我有这个文件 .json:

{
  "topologyTypes": {
    "stations": {
      "instances": [
        {
          "@name": "value1",
          "@address": "value2"
        },
        {
          "@name": "value3",
          "@address": "value4"
        }         
      ]
    }
  },
  "agg": {},
  "inter": {}
}
Run Code Online (Sandbox Code Playgroud)

我想使用 PowerShell 在拓扑类型.stations.instances 中添加这样的对象

{
    "@name": "value4",
    "@adress": "value5"
}
Run Code Online (Sandbox Code Playgroud)

所以我在 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)
Run Code Online (Sandbox Code Playgroud)

我想要得到的期望输出是这样的:

{
  "topologyTypes": {
    "stations": {
      "instances": [
        {
          "@name": "value1",
          "@address": "value2"
        },
        {
          "@name": "value3",
          "@address": "value4"
        },
        {
          "@name": "value4",
          "@address": "value5"
        }         
      ]
    }
  },
  "agg": {},
  "inter": {}
}
Run Code Online (Sandbox Code Playgroud)

Ans*_*ers 6

将新内容定义为 PowerShell 自定义对象:

$jsonContent = [PSCustomObject]@{
    '@name'   = 'value4'
    '@adress' = 'value5'
}
Run Code Online (Sandbox Code Playgroud)

将其附加到instances导入的 JSON 数据的子结构中:

$jsonFile.topologyTypes.stations.instances += $jsonContent
Run Code Online (Sandbox Code Playgroud)

然后将数据转换回 JSON 字符串:

$jsonFile | ConvertTo-Json -Depth 4
Run Code Online (Sandbox Code Playgroud)

请注意,ConvertTo-Json插入了大量的意图空间。如果您想要的正是您发布的格式,您需要自己进行一些漂亮的打印。像这样的事情可能会有所帮助。