Skip to content

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/getVmFacts from recipe 4.2, which returns a VM’s facts as Properties, and the vCenter vc01.vmw.lab registered with the vCenter plug-in.
  • A login that can create actions in com.vcfguide.chapter5.

How to do it

Build JSON

  1. In Library > Actions, create the action vmFactsToJson in com.vcfguide.chapter5, with the input vms of type Array/VC:VirtualMachine and the Return type string:
com.vcfguide.chapter5/vmFactsToJson
// 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);
  1. Run it with two VMs. The result is a JSON document with a vms array of two objects, indented by two spaces.
Figure 5.16. VM facts as JSON, built from Properties with explicit conversions.

Parse JSON

  1. Create the action parseVmFactsJson, with the input json of type string and the Return type Array/Properties:
com.vcfguide.chapter5/parseVmFactsJson
// 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;
  1. Copy the result of step 2, run parseVmFactsJson, and paste it into json. The result is an array of two Properties, and the log names the time the document was made.
  2. Run it again with {"vms": 1}. It fails with the document has no vms array, which is easier to act on than a TypeError three 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

  1. Create the action vmFactsToXml, with the input vms of type Array/VC:VirtualMachine and the Return type string:
com.vcfguide.chapter5/vmFactsToXml
// 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);
  1. Run it with the same two VMs. The result is an XML declaration, a vmFacts element, and one vm element for each VM. Characters such as & and < in a VM name are escaped for you.

Read XML

  1. Create the action readVmFactsXml, with the input xml of type string and the Return type Array/string:
com.vcfguide.chapter5/readVmFactsXml
// 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;
  1. Run it with the result of step 7. You get one line for each VM.
Figure 5.17. An XML document built with the XML plug-in, and read back.

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&amp;b&lt;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.

Back in vRO 5.5–7Parse and build XML with E4X: new XML(text), doc.vm.(@name == 'web01'), and XML literals in the script.
In Orchestrator 9.xUse the XML plug-in's 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