XML and JSON
Most of what a workflow sends and receives is text in one of two formats. REST APIs speak JSON, and so do message queues and most tools you’ll call from a script. XML is still the language of SOAP services, many network devices, older APIs, and configuration files. Orchestrator handles JSON with the JavaScript engine’s own JSON object, and XML with the XML plug-in.
In this recipe you write four small actions in com.vcfguide.chapter5: two that turn VM facts into JSON and back, and two that do the same with XML. They show the conversions that trip people up: plug-in objects that JSON.stringify writes as {}, Properties whose keys come out in no fixed order, and XML parsing that no longer works the way it did in vRO 7.
Getting ready
- The action
com.vcfguide.chapter4/getVmFactsfrom recipe 4.2, which returns a VM’s facts asProperties, and the vCentervc01.vmw.labregistered with the vCenter plug-in. - A login that can create actions in
com.vcfguide.chapter5.
How to do it
Build JSON
- In Library > Actions, create the action
vmFactsToJsonincom.vcfguide.chapter5, with the inputvmsof typeArray/VC:VirtualMachineand the Return typestring:
// Returns the facts of the VMs as a JSON document.var chapter4 = System.getModule("com.vcfguide.chapter4");
var document = { vcenter: "vc01.vmw.lab", generated: new Date().toISOString(), vms: []};for (var i = 0; i < vms.length; i++) { var facts = chapter4.getVmFacts(vms[i]); // Copy each value into a plain object: the keys keep this order, // and a plug-in object put in by mistake would become {}. document.vms.push({ name: String(facts.get("name")), powerState: String(facts.get("powerState")), cpus: Number(facts.get("cpus")), memoryMb: Number(facts.get("memoryMb")), guestOs: facts.get("guestOs") ? String(facts.get("guestOs")) : null });}return JSON.stringify(document, null, 2);- Run it with two VMs. The result is a JSON document with a
vmsarray of two objects, indented by two spaces.
Run of action com.vcfguide.chapter5/vmFactsToJson with two VMs: the result, an indented JSON document with vcenter, generated, and a vms array of two objects.
Parse JSON
- Create the action
parseVmFactsJson, with the inputjsonof typestringand the Return typeArray/Properties:
// Parses a document made by vmFactsToJson and returns one Properties// object per VM, so a workflow can bind the result to a variable.var document;try { document = JSON.parse(json);} catch (e) { throw "parseVmFactsJson: not valid JSON: " + e;}if (!document || !(document.vms instanceof Array)) { throw "parseVmFactsJson: the document has no vms array";}
var result = [];for (var i = 0; i < document.vms.length; i++) { var vm = document.vms[i]; var props = new Properties(); props.put("name", vm.name); props.put("powerState", vm.powerState); props.put("cpus", vm.cpus); props.put("memoryMb", vm.memoryMb); result.push(props);}System.log(result.length + " VMs in a document generated " + document.generated);return result;- Copy the result of step 2, run
parseVmFactsJson, and paste it intojson. The result is an array of twoProperties, and the log names the time the document was made. - Run it again with
{"vms": 1}. It fails with the document has no vms array, which is easier to act on than aTypeErrorthree lines later.
Checked on 9.1.1, with getVmFacts on one VM:
| Expression | JSON.stringify gives |
|---|---|
The Properties from getVmFacts |
{"memoryMb":2048,"guestOs":"Rocky Linux (64-bit)","powerState":"poweredOn","cpus":1,"name":"rockylinux9",…}, with the keys in no fixed order |
facts.get("name"), vm.name |
a plain JSON string; typeof is string |
vm, a VC:VirtualMachine |
{} |
vm.runtime.powerState, a vSphere enumeration |
{} |
new Date(0) |
"1970-01-01T00:00:00.000Z" |
So on 9.1.1 the copying in step 1 isn’t needed for Properties to show up at all, as it was in some earlier releases. It’s still worth doing: it fixes the order and the types of the fields, and it stops a plug-in object from turning into an empty {} without an error.
Build XML
- Create the action
vmFactsToXml, with the inputvmsof typeArray/VC:VirtualMachineand the Return typestring:
// Returns the facts of the VMs as an XML document, built with the XML plug-in.var chapter4 = System.getModule("com.vcfguide.chapter4");
var document = XMLManager.newDocument();var root = document.createElement("vmFacts");root.setAttribute("vcenter", "vc01.vmw.lab");document.appendChild(root);
for (var i = 0; i < vms.length; i++) { var facts = chapter4.getVmFacts(vms[i]); var vm = document.createElement("vm"); vm.setAttribute("name", String(facts.get("name"))); vm.setAttribute("powerState", String(facts.get("powerState"))); vm.setAttribute("cpus", String(facts.get("cpus"))); vm.setAttribute("memoryMb", String(facts.get("memoryMb"))); root.appendChild(vm);}return XMLManager.getDocumentContent(document);- Run it with the same two VMs. The result is an XML declaration, a
vmFactselement, and onevmelement for each VM. Characters such as&and<in a VM name are escaped for you.
Read XML
- Create the action
readVmFactsXml, with the inputxmlof typestringand the Return typeArray/string:
// Reads a document made by vmFactsToXml and returns one line per VM.var document = XMLManager.fromString(xml);var nodes = document.getElementsByTagName("vm");
var lines = [];for (var i = 0; i < nodes.length; i++) { var vm = nodes.item(i); lines.push(vm.getAttribute("name") + ": " + vm.getAttribute("powerState") + ", " + vm.getAttribute("cpus") + " vCPU, " + vm.getAttribute("memoryMb") + " MB");}return lines;- Run it with the result of step 7. You get one line for each VM.
Two runs side by side: vmFactsToXml with its XML result (declaration, vmFacts, two vm elements with attributes), and readVmFactsXml with that XML as input and two result lines.
Checked on 9.1.1: every call above works, the node list has length and item(i), and childNodes and textContent work as in a browser. getDocumentContent writes <?xml version="1.0" encoding="UTF-8" standalone="no"?> and the document on one line, with a&b<c in an attribute escaped as a&b<c.
How it works
JSON is part of the language. JSON.parse and JSON.stringify are in ECMAScript 5.1, so they need no plug-in. They work on JavaScript values: objects, arrays, strings, numbers, booleans, and null. Everything a plug-in hands you is something else: a Java object wrapped so that scripts can use it. Properties and VC:VirtualMachine are Java objects. On 9.1.1, JSON.stringify writes a Properties object as a JSON object, but a plug-in object such as a VM, or a vSphere enumeration such as vm.runtime.powerState, comes out as {}, with no error. Read the values you want, such as vm.name or vm.runtime.powerState.value, and put them into an object of your own, as step 1 does. Going the other way, JSON.parse gives plain values, and step 3 puts them into Properties because a workflow variable can’t hold a plain JavaScript object.
Check what you parse. JSON.parse only tells you the text is valid JSON. It doesn’t tell you the document has the shape you expect. Test for the fields you need straight after parsing, and throw an error that names what’s missing, as step 3 does.
The XML plug-in is a DOM parser. XMLManager creates and parses documents. A document is a tree of nodes, and you walk it with the same calls as the DOM in a web browser: getElementsByTagName, getAttribute, childNodes, textContent. When you build a document, the plug-in escapes text and attribute values and writes the XML declaration, so you never build XML by adding strings together.
new XML(text), doc.vm.(@name == 'web01'), and XML literals in the script.XMLManager. On 9.0.2, new XML(text) fails on a document that starts with an XML declaration, and Broadcom's fix is XMLManager.fromString(text) (KB 438656).On 9.1.1, Context.getImplementationVersion() reports Rhino 1.9.1. E4X still works there for a document without a declaration: new XML("<a><b id='1'>t</b></a>").b.@id gives 1. With a declaration, new XML(text) fails with The processing instruction target matching “[xX][mM][lL]” is not allowed, the error from KB 438656. Don’t write new code with E4X: it fails on the first document that arrives with a declaration, and Rhino may drop it in a later release.
There's more
JSON from a REST API. Recipe 5.2 parsed vCenter’s answer with JSON.parse(response.contentAsString). The same checks apply: test statusCode first, then parse, then check the fields. To send JSON, build a plain object, JSON.stringify it, and pass the string as the request’s content with the header Content-Type: application/json.
Field names with spaces or symbols. Some APIs use keys such as Asset ID or x-request-id. Read them with brackets: row["Asset ID"].
Big numbers. JavaScript numbers are 64-bit floating point, so an integer above 253, such as some object IDs and byte counts, loses its last digits in JSON.parse. If an API returns IDs as long numbers, ask for them as strings, or compare them as text.
Namespaces. SOAP replies and many vendor formats put every element in a namespace, such as <soap:Envelope>. getElementsByTagName("Envelope") won’t find it. Use the full name with the prefix the document uses, getElementsByTagName("soap:Envelope"), or the namespace-aware call, which doesn’t depend on the prefix: getElementsByTagNameNS("http://schemas.xmlsoap.org/soap/envelope/", "Envelope"). Both were checked on 9.1.1; the plain local name found nothing.
Files. XMLManager can also read and save XML files on the server. Only paths the server may write to work; on 9.x that is /var/run/vco (recipe 5.3). Store the content in a resource element instead if more than one run needs it.
Built-in samples. Search with the tag xml for the plug-in’s sample workflows. They build a small address book document and find elements in it, and their scripts are a quick reference to the DOM calls.
See also
- 4.1 The Rhino engine, for ES5.1 and Java objects in scripts.
- 5.2 REST hosts and operations, for JSON over HTTP.
- 5.7 AMQP and messaging, which sends these JSON documents as messages.
- Broadcom TechDocs (VCF 9.0): Plug-ins installed with the VCF Operations orchestrator server, which describes the XML plug-in as a DOM parser, and Using the XML plug-in.
- Broadcom KB 438656:
new XML()fails in 9.0.2; useXMLManager.fromString. - Broadcom KB 454667: action inputs and outputs,
Properties, and composite types. - ECMAScript 5.1: The JSON object.
- CloudBlogger, the author’s blog: Getting Started with Cisco UCS Manager REST API Using XML in Orchestrator.
