Using JavaScript to parse JSON properties with Ant

I’ve been automating my iOS build systems using various tools such as Xcodebuilder, Ant, Applescript and several plugins. I want to use a common format for settings across the various scripts so I picked JSON because I could easily parse it in each instance.

Apace Ant is a command-line tool that is commonly used to build files as targets that are dependent upon each other. I first came across Ant when working with Android projects and wanted to incorporate a similar process into my iOS projects. Ant uses Rhino as the JavaScript interpreter in the script task so I would suggest reading up on the Rhino documentation if you’re attempting this.

To get you started, here’s an quick Ant build example that will parse a simple JSON object in properties.json and set those properties in the Ant project.

properties.json (in a Gist):


The Ant build.xml file (in a Gist):

<?xml version="1.0" encoding="UTF-8"?>
<project name="JSON Example" basedir=".">
    <script language="javascript">
        echo = project.createTask("echo");
        echo.setMessage("Parsing properties");
        var file = new File("properties.json");
        fr = new FileReader(file);
        br = new BufferedReader(fr);
        // Read the file. 
        // This assumes the file has no line breaks and is one line.
        var json = br.readLine();
        // Evaluate the JSON.
        var struct = eval("(" + json + ")");
        // Set each property in the project environment.
        for (i in struct) {
            echo = project.createTask("echo");
            echo.setMessage(i + "=" + struct[i]);
    <target name="example">
        <echo>${greeting} ${audience}</echo>

And the result (in a Gist):

Jeffreys-MacBook-Air$ ant example
Buildfile: /Users/jsambells/Documents/example/build.xml
    [echo] Parsing properties
    [echo] greeting=Hello
    [echo] audience=world
    [echo] Hello world

You can remove some of the echo statements in a production script but this shows how to set the properties in Ant from JavaScript. You can use project.getProperty('name') to retrieve existing properties from Ant in the <script> if you need. Now you can use JSON directly from a url or file to set the environment in your Ant build.