0

I am trying to create a script that will copy some Django permissions, modify them and then re-apply them to our instance.

I appear to have no problems reading / writing the requests, with the exception of the permissions "constraints" value. This value needs to be sent in the form of a JSON query. It appears that as the actual POST action itself needs to be performed as a JSON query, the Invoke-WebRequest cmdlet is modifying the nested JSON and adding escape characters.

An example of the POST code in question is below (the remaining part of the script appears fine and is long so have not included however can do so if needed):

$PostBody  = @{'name' = $newPermName
               'groups' = @($queGroupIDResult.results[0].id[0]) | ConvertTo-Json
               'actions' = ConvertTo-Json @($subTempResult.actions)
               'constraints' = @($subtempresult.constraints) | ConvertTo-Json}
        
Try  {$postResponse = Invoke-RestMethod -Body $PostBody -Headers @{ 'Authorization' = "Token $strapikey" } -Method Post -URI "$strserverurl/api/users/permissions/"
      Write-Host "--- Permission built"} #-ContentType 'application/json' 
Catch{Write-Host -ForegroundColor Red "--- There was an error performing the API post query"}

An example of the 'constraints' value is:

@($subtempresult.constraints) | ConvertTo-Json
{
 "slug": "strsiteslug"
}

However when this is sent via Invoke-WebRequest it appears in the Django backend as:

"[\r\n {\r\n \"slug\": \"strsiteslug\"\r\n }\r\n]

If I do not ConvertTo-Json the @($subtempresult.constraints) value, then I just see SystemObject[] in the django backend.

I'm not really sure where to go from here, it feels as though I've tried every which way / combination of splatting / converting the variables before I try and post them with no success.

Sam H
  • 262
  • 1
  • 15
  • Apparently Django doesn't like 'pretty' JSON. Have you tried `ConvertTo-Json -Compress` ? – Theo Dec 17 '20 at 11:11
  • 2
    Remove `ConvertTo-Json` from inside the hashtable and apply it to all of `$postBody` instead (you may have to specify a `-Depth` to convert the leaf values properly) – Mathias R. Jessen Dec 17 '20 at 11:59
  • @MathiasR.Jessen that was the issue, feel free to add as answer and I will mark it. – Sam H Dec 17 '20 at 13:27
  • Does this answer your question? [Unexpected ConvertTo-Json results? Answer: it has a default -Depth of 2](https://stackoverflow.com/questions/53583677/unexpected-convertto-json-results-answer-it-has-a-default-depth-of-2) – iRon Dec 17 '20 at 17:50

0 Answers0