DEV Community

Cover image for Convert XML to JSON in 1 line of code using ColdFusion
James Moberg
James Moberg

Posted on • Updated on

Convert XML to JSON in 1 line of code using ColdFusion

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.

https://www.trycf.com/gist/00bb362672f772fab56d26f3e01ad3fa/acf11

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.

https://gist.github.com/JamoCA/00bb362672f772fab56d26f3e01ad3fa

2019-11-13: 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.

2023-07-25: This approach to consuming XML is not susceptible to the XML External Entity (XXE) vulnerability.
https://foundeo.com/security/guide/xml-external-entities/

Oldest comments (0)