J. Sam
J. Sam

Reputation: 65

How to add an object in array on parsed JSON?

I have this file .json:

{
  "topologyTypes": {
    "stations": {
      "instances": [
        {
          "@name": "value1",
          "@address": "value2"
        },
        {
          "@name": "value3",
          "@address": "value4"
        }         
      ]
    }
  },
  "agg": {},
  "inter": {}
}

I want to add an object like this in topologyType.stations.instances with PowerShell

{
    "@name": "value4",
    "@adress": "value5"
}

So I tried this following code in PowerShell, but it doesn't work:

$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)

The desired output I would like to get is like this:

{
  "topologyTypes": {
    "stations": {
      "instances": [
        {
          "@name": "value1",
          "@address": "value2"
        },
        {
          "@name": "value3",
          "@address": "value4"
        },
        {
          "@name": "value4",
          "@address": "value5"
        }         
      ]
    }
  },
  "agg": {},
  "inter": {}
}

Upvotes: 1

Views: 3238

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200273

Define the new content as a PowerShell custom object:

$jsonContent = [PSCustomObject]@{
    '@name'   = 'value4'
    '@adress' = 'value5'
}

append it to the instances substructure of your imported JSON data:

$jsonFile.topologyTypes.stations.instances += $jsonContent

then convert the data back to a JSON string:

$jsonFile | ConvertTo-Json -Depth 4

Note that ConvertTo-Json inserts a lot of intention space. If you want exactly the format you posted you need to do some pretty-printing yourself. Something like this might help.

Upvotes: 6

Related Questions