Post the XML file, not a screenshot of it!
Converting XMLBody to JSONBody for POSTing a request to WebAPI
Hi Team,
I have a PowerShell code which has a XML body structure as follows to make a webservice call.
I would like to include more inputs to the "Initialize Data" activity in one of the Runbook as follows.
To accommodate these newly added fields in the POSTBody and make it more readable, I would like to convert this to the JSON format as below format for all the fields as shown above.
{"RunbookId": "aba22216-e183-4e6b-ba76-de87991eb57e", "Parameters": "<Data><Parameter><Name>UserDistinguishedName</Name><ID>{e9bc0d73-89ef-478e-9db4-09ffbcceba6b}</ID><Value>${UserDistinguishedName}</Value></Parameter></Data>"}
I tried the below command and it is not exactly showing the output as I expected.
$JSONBody = $POSTBody | Convertto-Json
It would be great if someone helped in creating a JSON Body request format for all the fields.
Regards,
Jansi
2 answers
Sort by: Most helpful
-
-
Rich Matheisen 45,111 Reputation points
2021-06-13T19:37:03.613+00:00 You can try using the ConvertFrom-Xml helper function from here: convert-multiple-xmls-to-json-list
Using a stripped-down version of your XML, the code looks like this:
[xml]$PostBody = @" <entry> <content> <properties> <runbookid>12345-6803</runbookid> <parameters>SomeStuffHere</parameters> </properties> </content> </entry> "@ # Helper function that converts a *simple* XML document to a nested hashtable # with ordered keys. function ConvertFrom-Xml { param([parameter(Mandatory, ValueFromPipeline)] [System.Xml.XmlNode] $node) process { if ($node.DocumentElement) { $node = $node.DocumentElement } $oht = [ordered] @{} $name = $node.Name if ($node.FirstChild -is [system.xml.xmltext]) { $oht.$name = $node.FirstChild.InnerText } else { $oht.$name = New-Object System.Collections.ArrayList foreach ($child in $node.ChildNodes) { $null = $oht.$name.Add((ConvertFrom-Xml $child)) } } $oht } } $postbody | convertfrom-xml | convertto-json -depth 10
The result looks like this:
"entry": [ { "content": [ { "properties": [ { "runbookid": "12345-6803" }, { "parameters": "SomeStuffHere" } ] } ] } ] }