I was researching methods of converting XML to JSON using ColdFusion. I didn't want to use xmlParse() because I didn't want to have to iterate over an XML object. CoolUtils offers a GUI/commandline Total XML Converter that is capable of converting XML to JSON, CSV and SQL code. (Very cool indeed!) I found a couple other possibilities like Xidel, but it required that I provide a fair amount of information in order to convert.
I found a java blog entry titled "Java library to convert XML to JSON" and thought it was worth checking out. While adding the JAR to my server, I noticed that it worked without having to reboot. I thought it may have loaded automatically, but soon determined it was due to the fact that CF2016's "cfusion/lib/closure-compiler.jar" already supports the same "org.json.xml" class files. This means that I only need to download the most recent JSON jars if I wanted to upgrade a couple of older CF10 servers.
I've tested it with some USPS, real estate and RSS XML files and it seems to work ok. I noticed that some numeric values were converted to scientific notation in the JSON file and I'm going to review to determine if this is normal or not, but other than that it was extremely fast and will hopefully be easier to consume and make it easier to exchange data with other APIs.
Here's some sample CFML code.
While testing this online in order to share, I noticed that the official Adobe CFFiddle doesn't allow
createObject() which means you can really only test this on TryCF.com. I also noticed that it didn't work on Lucee, but only because they don't have the supporting Java libraries installed.
NOTE: If you want to retain XML numbers, you'll need to use JavaLoader and use a newer version of JSON-Java that supports a secondary "true" argument. This will safely convert number values to text strings instead of converting to scientific notation or rounding.
Here's the CFML source code on gist.
11/13/2019: I tested this technique against some OWASP malicious XML samples and the good data was parsed without any error while the bogus data appeared to be ignored. Both ColdFusion's xmlparse and Foundeo's SafeXMLParse encountered parsing issues and returned an error.
Top comments (0)