0

My problem is that I have a remote API giving me a JSON with 10 levels deep nesting and I need to add another array/hashtable/PSCustomObject (whatever you want to call it) to one of them.

The JSON looks like this:

{  
  "result": [  
    "modules": [  
      "data": {  
        "segments": [  
          {  
            "routes": {  
              "static": [  
                {  
                  "destination": "10.0.0.0",
                  "netmask": "255.0.0.0"
                },
                {  
                  "destination": "172.16.0.0",
                  "netmask": "255.240.0.0"
                }  
              ]  
            }  
          }  
        ]  
      }  
    ]  
  ]  
}  

The return object is a Hashtable, however when I try to access the values in dot notation, it turns into PSCustomObject:

$statics = $result.result.modules.data.segments.routes.static

It won't let me use the other notation:

$statics = $result['result']['modules']['data']['segments']['routes']['static']
Error: Cannot index into a null array

The real tricky part (for me) is to to append a new hastable to the "static" hashtable in such a way that the rest of the hashtable remains intact.

$newroute = @{
    destination = "1.1.1.1."
    netmask = "255.255.255.255"
}

I would have used PHP or Python but for this project I must use Powershell and I'm running into all sorts of things where PS behaves different from what I expect.

Any help is greatly appreciated!

1 Answer 1

2

static is an array, you can add new items to it:

$newStaticRoute = [pscustomobject]@{
  destination = '192.168.0.0'
  netmask = '255.255.0.0'
}

$result.result.modules.data.segments.routes.static += $newStaticRoute
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.