Hello everyone,
I have created a workflow that will pull down data via a RESTful API in JSON, then my code parses and modifies said data. The problem I have is that these APIs I am working with only accept XML to PUT/POST data, and I am looking for an easy way to convert my JSON file to XML.
I did a search on the forums here and google searched a bit and did not find a solution to my problem yet. My preferred language is shell/bash, and while I did find some Python code that does this, my whole work flow is written in shell and uses jq.
Any ideas on how to convert a JSON file to XML in bash? I am hoping I don't have to build the XML on the fly and can just convert it.
I am working on OS X and Debian Wheezy and Ubuntu 14 if that matters. My computer is a Mac that has several VMs of Linux running.
If you can install PHP you may try this its easy
[akshay@localhost JSON2XML]$ cat test.php
<?php
/**
* Convert JSON to XML
* @param string - json
* @return string - XML
*/
function json_to_xml($json)
{
include_once("XML/Serializer.php");
$options = array (
'addDecl' => TRUE,
'encoding' => 'UTF-8',
'indent' => ' ',
'rootName' => 'json',
'mode' => 'simplexml'
);
$serializer = new XML_Serializer($options);
$obj = json_decode($json);
if ($serializer->serialize($obj)) {
return $serializer->getSerializedData();
} else {
return null;
}
}
$sample = <<<EOF
{"menu": {
"id": "file",
"value": "File",
"popup": {
"menuitem": [
{"value": "New", "onclick": "CreateNewDoc()"},
{"value": "Open", "onclick": "OpenDoc()"},
{"value": "Close", "onclick": "CloseDoc()"}
]
}
}}
EOF;
echo json_to_xml($sample);
?>
[akshay@localhost JSON2XML]$ php test.php
<?xml version="1.0" encoding="UTF-8"?>
<json>
<menu>
<id>file</id>
<value>File</value>
<popup>
<menuitem>
<value>New</value>
<onclick>CreateNewDoc()</onclick>
</menuitem>
<menuitem>
<value>Open</value>
<onclick>OpenDoc()</onclick>
</menuitem>
<menuitem>
<value>Close</value>
<onclick>CloseDoc()</onclick>
</menuitem>
</popup>
</menu>
</json>
There are a number of Python libraries than will convert JSON to XML