Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

parse json with ant

Tags:

json

ant

I have an ant build script that needs to pull files down from a web server. I can use the "get" task to pull these files down one by one. However, I'd like to be able to get a list of these files first and then iterate over the list with "get" to download the files. The webserver will report the list of files in json format, but I'm not sure how to parse json with ant.

Are there any ant plugins that allow for json parsing?

like image 837
paleozogt Avatar asked Mar 26 '10 21:03

paleozogt


3 Answers

I used Dave's suggestion above and it worked out pretty well. Here's what I came up with:

(Note, I ripped this out of my actual build file and tried to remove anything specific and just leave the example parts, so forgive me if it's missing anything or whatever, but it should give you an idea of how this works).

<?xml version="1.0"?>

<project name="jsonExample" default="all">
<target name="all" depends="example" />

<target name="example">

<!-- This uses Rhino - an Open Source implementation of JavaScript written in Java -
     to parse JSON. -->
<script language="javascript"> <![CDATA[

    importClass(java.io.File);
    importClass(java.io.FileReader);
    importClass(java.io.BufferedReader);
    importClass(java.io.FileWriter);
    importClass(java.io.BufferedWriter);

    var file = new File("/path/to/myJSON.js");
    fr = new FileReader(file);
    br = new BufferedReader(fr);

    // Read the file we just retrieved from the webservice that contains JSON.
    var json = br.readLine();

    // Evaluate the serialized JSON
    var struct = eval("(" + json + ")");

    // Get the data from 
    var value = struct.data.VALUE;

    echo = example.createTask("echo");
    echo.setMessage("Value = " + value);
    echo.perform();

    ]]>
</script>
</target>

like image 148
bdetweiler Avatar answered Oct 12 '22 12:10

bdetweiler


You can use a <script> task to run JavaScript to decode your JSON.

like image 37
leedm777 Avatar answered Oct 12 '22 12:10

leedm777


Here is the macro I use to load json-properties.

 <macrodef name="json-properties">
     <attribute name="jsonFile"/>
     <sequential>
         <local name="_jsonFile"/>
         <property name="_jsonFile" value="@{jsonFile}"/>
         <script language="javascript">//<![CDATA[
             var json = new Packages.java.lang.String(
                 Packages.java.nio.file.Files.readAllBytes(
                     Packages.java.nio.file.Paths.get(project.getProperty("_jsonFile"))), "UTF-8");
             var properties = JSON.parse(json);
             for(key in properties) {
                 project.setProperty(key, properties[key]);
             }
     //]]></script>
     </sequential>
 </macrodef>
like image 23
TJR Avatar answered Oct 12 '22 13:10

TJR