One of the great things about Apps Script is that you can use the content service to create your own apis, without the need for a server infrastructure. In From Xml to JSON and Convert JSON to XML I showed how to use Apps Script to convert between json and api. Now here is that code wrapped up in a web app, which means you can call it from any language, either passing some json and getting xml back, or the other way round.

You can also use it from apps script of course – useful if you get xml back from some API but would rather have JSON.

How to use

First of all, you’ll need the URL of the web app. It’s publicly published here, if you want to use my version.

or you can make your own by getting the code off github.

It supports both GET and POST and will take an optional parameter, callback=, if you want JSONP rather than JSON from an XML to JSON conversion. The data to be converted is passed with the convert= parameter which is mandatory. The direction of conversion is automatically detected from the data sent.

In the examples following we have a variable to which the converter webapp url has been assigned.

Here’s an example using POST from another Apps Script app. In this example, first I get some XML from an API that returns XML, then call the converter web app to turn that into JSON.

and here’s the result

Now, we’ll try getting the result in JSON. There is no difference in the code, aside from the request to get xml rather than JSON. The converter detects automatically which type of conversion is needed, so in this case it will detect it has been handed some JSON and will convert it to XML.

The result in XML

Using GET

You can use GET rather than POST for small payloads. This example takes an xmlString and passes it to the webapp for conversion to JSON. The data should be encoded and passed as the convert parameter like this.

The code

You’ll get the code off GitHub for the webapp if you need it. Here’s some examples of using it. The conversions alogorithms are also available at From Xml to JSON and Convert JSON to XML

Here’s an example of converting a file on drive from xml to json

For more like this see Google Apps Scripts Snippets
Why not join our forum, follow the blog or follow me on Twitter to ensure you get updates when they are available.