0

I have the following JSON

{
  "method": "exec",
  "params": [
    {
      "url": "/sys/login/user",
      "data": [
        {
          "user": "MyUsername",
          "passwd": "MyPassword"
        }
      ]
    }
  ],
  "id": 1,
  "ver": "2.0"
}

I'm trying to build this JSON using Powershell, but the output is not correct, below is my code.

$fullJson=@{}
$params=@()
$paramsdata=@()
$paramsdata+=@{"user"="mailapi"}
$paramsdata+=@{"passwd"="**********"}
$params+=@{"url"="/sys/login/user"}
$params+=@{"data"=$paramsdata}
$fullJson.Add("method", "exec")
$fullJson.Add("params",$params)
$fullJson.Add("id", "1")
$fullJson.Add("ver", "2.0")
$JsonBody=$fullJson | ConvertTo-Json
$x=Invoke-WebRequest -Uri https://10.10.10.10/jsonrpc -Body $JsonBody -Method Post

The output is the below

{
    "method":  "exec",
    "params":  [
                   {
                       "url":  "/sys/login/user"
                   },
                   {
                       "data":  "System.Collections.Hashtable System.Collections.Hashtable"
                   }
               ],
    "id":  "1",
    "ver":  "2.0"
}

The problem is DATA properties is not correct format, it should be an a nested array inside the first one, but it seems that its being added as a hashtable.

This problem is the data array should be built like this one below

"params": [
    {
      "url": "/sys/login/user",
      "data": [
        {
          "user": "MyUsername",
          "passwd": "MyPassword"
        }
      ]

But with my code, its being built like this

"params":  [
                   {
                       "url":  "/sys/login/user"
                   },
                   {
                       "data":  "System.Collections.Hashtable System.Collections.Hashtable"
                   }
               ],

Any help in updating this.

Thanks

1 Answers1

0

Use the -Depth option in ConvertTo-Json :

Specifies how many levels of contained objects are included in the JSON representation. The default value is 2.

Your desired depth is 4 (object -> params -> data -> username/password) :

$JsonBody=$fullJson | ConvertTo-Json -Depth 4
Fourat
  • 2,366
  • 4
  • 38
  • 53
  • The Code should be sent like this ``` "params": [ { "url": "/sys/login/user", "data": [ { "user": "MyUsername", "passwd": "MyPassword" } ] ``` But using my code, it's being built like this ``` "params": [ { "url": "/sys/login/user" }, { "data": "System.Collections.Hashtable System.Collections.Hashtable" } ], ``` – Faris Mlaeb Nov 18 '19 at 10:28
  • @FarisMlaeb I misunderstood your question and now I have edited my answer. – Fourat Nov 18 '19 at 10:49