Skip to content

Commit

Permalink
MapTag.to_json and to_yaml
Browse files Browse the repository at this point in the history
  • Loading branch information
mcmonkey4eva committed May 11, 2020
1 parent 6c2c623 commit 4750532
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@
import com.denizenscript.denizencore.tags.TagContext;
import com.denizenscript.denizencore.tags.TagRunnable;
import com.denizenscript.denizencore.utilities.CoreUtilities;
import com.denizenscript.denizencore.utilities.YamlConfiguration;
import com.denizenscript.denizencore.utilities.debugging.Debug;
import com.denizenscript.denizencore.utilities.text.StringHolder;
import org.json.JSONObject;

import java.util.LinkedHashMap;
import java.util.Map;
Expand Down Expand Up @@ -325,6 +327,28 @@ public static void registerTags() {
}
return result;
});

// <--[tag]
// @attribute <MapTag.to_json>
// @returns ElementTag
// @description
// Returns a JSON encoding of this map.
// -->
registerTag("to_json", (attribute, object) -> {
return new ElementTag(new JSONObject((Map) CoreUtilities.objectTagToJavaForm(object.duplicate(), false)).toString());
});

// <--[tag]
// @attribute <MapTag.to_yaml>
// @returns ElementTag
// @description
// Returns a YAML encoding of this map.
// -->
registerTag("to_yaml", (attribute, object) -> {
YamlConfiguration output = new YamlConfiguration();
output.contents = (Map) CoreUtilities.objectTagToJavaForm(object.duplicate(), true);
return new ElementTag(output.saveToString(false));
});
}

public static ObjectTagProcessor<MapTag> tagProcessor = new ObjectTagProcessor<>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,30 @@ else if (obj instanceof Map) {
}
}


public static Object objectTagToJavaForm(ObjectTag obj, boolean stringHolder) {
if (obj == null) {
return null;
}
else if (obj instanceof ListTag) {
List<Object> output = new ArrayList<>(((ListTag) obj).size());
for (ObjectTag entry : ((ListTag) obj).objectForms) {
output.add(objectTagToJavaForm(entry, stringHolder));
}
return output;
}
else if (obj instanceof MapTag) {
Map<Object, Object> output = new LinkedHashMap<>();
for (Map.Entry<StringHolder, ObjectTag> entry : ((MapTag) obj).map.entrySet()) {
output.put(stringHolder ? entry.getKey() : entry.getKey().str, objectTagToJavaForm(entry.getValue(), stringHolder));
}
return output;
}
else {
return obj.toString();
}
}

public static String splitLinesByCharacterCount(String str, int length) {
if (length < 3) {
return str;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ else if (obj instanceof Map) {
return config;
}

Map<StringHolder, Object> contents;
public Map<StringHolder, Object> contents;
boolean dirty;

/**
Expand Down

0 comments on commit 4750532

Please sign in to comment.