I use Gson in java to generate json output, but Gson does not allow me to put javascript functions in json. So here is what I am doing: use replacement tags for the places where you want to put the code (for example, one of the early answers). Then get the json text, replace the tags and save the text in a json file:
Map<String, String> dynamicDates = new HashMap<>(); dynamicDates.put("d1", "new Date()"); dynamicDates.put("d2", "new Date(2015, 0, 1, 9, 30)"); dynamicDates.put("d3", "new Date(2015, 0, 1, 12, 30)"); JsonObject json = new JsonObject(); JsonObject root = new JsonObject(); JsonObject level_1_A = new JsonObject(); JsonObject level_1_B = new JsonObject(); json.add("root", root); root.add("level_1_A", level_1_A); root.add("level_1_B", level_1_B); level_1_A.addProperty("d1", "${d1}"); level_1_A.addProperty("d2", "${d2}"); level_1_B.addProperty("d3", "${d3}"); StringBuilder sb = new StringBuilder(); new GsonBuilder().setPrettyPrinting().create().toJson(json, sb); String str = sb.toString(); for (String key : dynamicDates.keySet()) { str = str.replace("\"${" + key + "}\"", dynamicDates.get(key)); } String jsonText = str; String javascriptText = "var myJson = " + str + ";"; System.out.println(jsonText); System.out.println(javascriptText);
Thus, there is nothing left to do on the consumption side when using this json. And the first conclusion:
{ "root": { "level_1_A": { "d1": new Date(), "d2": new Date(2015, 0, 1, 9, 30) }, "level_1_B": { "d3": new Date(2015, 0, 1, 12, 30) } } }
My use of json usually saves it as job javascript, so this works for me.
Fai ng
source share