Node-RED and XML to JSON

I’m trying to catch up with a whole load of stuff I did before I started this blog; as much as anything, so I can remember what I did for when I need to do it again!

Following on from installing Monit, I wanted to use Node-RED to monitor Monit so that ultimately I can have a dashboard for all sorts of things to be monitored and possibly alerts (rather than Monit doing that directly).

As previously mentioned, Monit communicates via an http interface so extracting the data was remarkably simple. All you need is a websocket flow and a URL like http://x.x.x.x:2812/_status?format=xml . It seemed that the obvious way to use this data was to convert the XML to JSON.

However, when I tried the built-in XML parser it did not work. Some digging brought up the fact that this built-in node has a limited depth. Not very useful. Further research led me to the xml2json node on npm. I’d never really understood the relationship between npm and Node-RED. What I think I understand is that Node-RED uses some command line nodes from npm which in itself is a Javascript package manager.

So in order to use this command line node (rather than a Node-RED flow) I needed to install it then ‘require’ it. The whole Javascript ecosystem is rather alien to me at the moment so getting it installed took a fair bit of experimenting although it is actually very simple to do.

It comprises of 3 steps:

  1. Install the node from npm. As you want to use it from Node-RED, you need to *not* install it globally – counter-intuitive right? So simply go into your node red folder (usually ~/.node-red) and then npm install xml2json (reference).
  2. Next, you need to edit your settings.js file to ‘require’ the node (reference). This file is also usually found in the ~/.node-red directory.
    Look for the functionGlobalContext and add in a line for the xml2json node.

    Save and restart Node-RED sudo service nodered restart .
  3. Add the code into a function such as:

This will now enable you to take an XML flow and break it down into its constituent parts

The complete Node-RED flow:

 

Facebooktwitterby feather
This entry was posted in Coding and Programming, Node-RED and tagged , , , . Bookmark the permalink.

Leave a Reply