How to build a json in powershell

Asked

Viewed 241 times

0

I am creating a Powershell script that calls the POST method a REST API.

Body sends a string representing a JSON object with the parameters that will be inserted by the API.

Do you know how I can Powershell escape a string representing a JSON object?

Excerpt from the script I have:

$jsonStr = "{""Nickname"":""$nickname"", ""Type"" : ""$type""}"

$content = New-Object System.Net.Http.StringContent $jsonStr

$content.Headers.ContentType = "application/json"

$task = $client.PostAsync($uriPost.Replace("{profid}", $profileId), $content)

$result = $task.GetAwaiter().GetResult()

Only this way, if the nickname has a " or / error. How can I escape the jsonStr?


Solution:

I think I’ve got a solution:

    $userProperties = @{
        nick = $name
        type = $type 
    }

    $jsonPayload = $userProperties | ConvertTo-Json     

Convert-Json already makes the necessary escape.

  • What error happens? There is no problem with the script itself, the bar is normal inside JSON

  • In the above script neither / am inserting. I do not do any escape type.

  • @Lucy, usually when Oce himself finds the solution, Oce put as a response and marks this as the solution accepted by Oce. So people who have the same doubt can find the answer accept faster :)

2 answers

1

Da para fazer escape of the value of your variables using the function:

[System.Security.SecurityElement]::Escape

Before you ride your JSON, call this function to the values of its variables, leaving something more or less like this:

$nickname = [System.Security.SecurityElement]::Escape('"teste"')
$jsonStr = "{""Nickname"": ""$nickname""}"
Write $jsonStr

The result will be this:

{"Nickname": ""teste""}
  • I edited the question, solved the problem with Converttojson from a dictionary.

0

This is the way to escape powershell quotes to create a string that represents your json

$jsonStr =@"
{"Nickname":"$nickname", "Type" : "$type"}
"@

Browser other questions tagged

You are not signed in. Login or sign up in order to post.