Reputation: 317
I'm trying to pass json into a REST api call in order to start builds on VSTS.
The body has two parameters that are passed in as an escaped string and i'm struggling to update the parameters before invoking my request. An example of my body is below:
$body ='
{
"definition":
{
"id": ""
},
"parameters": "{\"environment\":\"uat\", \"browser\": \"ie\"}"
}
'
This is passed into the following where I update the definition id successfully:
$bodyJson=$body | ConvertFrom-Json
$bodyjson.definition.id = $buildDefId
$bodyString=$bodyJson | ConvertTo-Json -Depth 100
This works successfully but I can't access the parameters element of the json in order to pass the browser and environments in as variables.
Do you have any suggestions on how to do this?
I have tried the following without success:
$params = $bodyJson.Paramaters
$params -replace "uat","test"
$bodyString=$bodyJson | ConvertTo-Json -Depth 100
This updates the parameter in $params
but it isn't passed back into the json when converted. I feel that i'm close but obviously missing a step.
Upvotes: 1
Views: 851
Reputation: 23862
Apparently you have a Json (parameters
) string embedded in another Json string.
Meaning that you have to ConvertFrom-Json
twice to deserialize everything and ConvertTo-Json
twice to serialize it back with the new parameters:
(Note that I swapped the variable names $body
and $bodyJson
because $body
is an object and $bodyJson
is actually your Json string)
$bodyJson = '
{
"definition": {
"id": ""
},
"parameters": "{\"environment\":\"uat\", \"browser\": \"ie\"}"
}
'
$body = $bodyJson | ConvertFrom - Json
$paramJson = $body.parameters
$parameters = $paramJson | ConvertFrom - Json
$parameters
environment browser
----------- -------
uat ie
Change the parameter:
$parameters.environment = "test"
And rebuild the Json string:
$paramJson = $parameters | ConvertTo-Json -Compress
$body.parameters = $paramJson
$bodyJson = $body | ConvertTo-Json
$bodyJson
{
"definition": {
"id": ""
},
"parameters": "{\"environment\":\"test\",\"browser\":\"ie\"}"
}
Upvotes: 3