Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@JamoCA
Last active July 25, 2023 16:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JamoCA/00bb362672f772fab56d26f3e01ad3fa to your computer and use it in GitHub Desktop.
Save JamoCA/00bb362672f772fab56d26f3e01ad3fa to your computer and use it in GitHub Desktop.
Convert XML string to JSON string in 1 line of code.
<!--- 2018-12-03 Convert XML string to JSON string in 1 line of code
Uses CF2016 /cfusion/lib/closure-compiler.jar (but library used is from 2009 and has been updated 12+ times)
If using CF10 (or want to use newer library), download newer JARs directly from the JSON-Java project & use JavaLoader:
https://github.com/stleary/JSON-java
https://search.maven.org/search?q=g:org.json%20AND%20a:json&core=gav
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/
--->
<cfsavecontent variable="xmlText"><note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
<thisisaNumber>1234567890</thisisaNumber>
</note>
</cfsavecontent>
<!--- Here's the "1 line of code" --->
<cfset jsonText = createobject("java", "org.json.XML").toJSONObject(xmlText)>
<!--- if you want numbers to not be converted to scientific notation, use updated JSON-java library and pass "true" as 2nd argument.
<cfset jsonText = createobject("java", "org.json.XML").toJSONObject(xmlText, true)>
--->
<cfset jsonObject = deserializejson(jsonText)>
<cfoutput>
<h2>XML</h2>
<textarea style="width:90%; height:50px;">#xmlText#</textarea>
<h2>JSON</h2>
<textarea style="width:90%; height:50px;">#jsonText#</textarea>
</cfoutput>
<h2>Object</h2>
<cfdump var="#jsonObject#" label="JSON Object">
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment