We do a lot of stuff using JSON as our data interchange format, in fact its becoming the most useful way of sending data around in our internal systems and putting the JSON data into a Rabbit MQ queue has allowed this data to be generated from our servers and get processed elsewhere with no issues as to transport and delivery.

Today I needed to quickly output a list of values stored in a JSON string into a HTML format for display on a static web page in our wiki, the extract program was a shell script that collects the JSON data from a queue and then for each JSON string, it needed to pluck the values out.

Python to the rescue!

As the collection script is a shell script, I looked for a standard Linux utility present on the server that I could use, quickly I realized that Python is on all our servers and it had a 1 line JSON processor that gives an array you can reference to retrieve the data.


import json
import fileinput
import sys

from pprint import pprint

def Process( jsondata ):
 data = json.loads(jsondata)
 host = "<tr><td><ac:link><ri:page ri:content-title=\""+data["host"]+"\"/>";
 print host,
 host2 ="<ac:plain-text-link-body><![CDATA["+data["host"]+"]]></ac:plain-text-link-body></ac:link></td>";
 print host2,
 print "<td style=\"text-align: center;\">",data["ctot"],"</td>",
 print "<td style=\"text-align: center;\">",data["ctused"],"</td>",
 print "<td style=\"text-align: center;\">",data["vtot"],"</td>",
 print "<td style=\"text-align: center;\">",data["vmused"],"</td>",
 print "</tr>"

for line in fileinput.input():Process( line );

The data

For the curious, the JSON data looks like this: