Skip to content

Instantly share code, notes, and snippets.

@iamamused
Created February 21, 2012 03:10
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iamamused/1873327 to your computer and use it in GitHub Desktop.
Save iamamused/1873327 to your computer and use it in GitHub Desktop.
Set Ant build properties from JSON

Example:

Jeffreys-MacBook-Air$ ant example
Buildfile: /Users/jsambells/Documents/example/build.xml
    [echo] Parsing properties
    [echo] greeting=Hello
    [echo] audience=world
example:
    [echo] Hello world
<?xml version="1.0" encoding="UTF-8"?>
<project name="JSON Example" basedir=".">
<script language="javascript">
importClass(java.io.File);
importClass(java.io.FileReader);
importClass(java.io.BufferedReader);
importClass(java.io.FileWriter);
importClass(java.io.BufferedWriter);
echo = project.createTask("echo");
echo.setMessage("Parsing properties");
echo.perform();
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]);
echo.perform();
project.setProperty(i,struct[i]);
}
</script>
<target name="example">
<echo>${greeting} ${audience}</echo>
</target>
</project>
{"greeting":"Hello","audience":"world"}
@dexbol
Copy link

dexbol commented May 14, 2012

It's useful , hope Ant can provide 'json-parse / json-stringify' task

@jadar
Copy link

jadar commented Jul 22, 2013

I can't seem to get it to work correctly. It seems to parse correctly because it echos it out, but I can't access the property.

@cm325
Copy link

cm325 commented Jan 19, 2017

I'm getting:

javax.script.ScriptEngineFactory: Provider com.sun.phobos.script.javascript.RhinoScriptEngineFactory could not be instantiated

How did you setup ant to start running tasks like this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment