changeset 1115:809d74db1415

add json_pretty_string
author Franklin Schmidt <fschmidt@gmail.com>
date Thu, 03 Aug 2017 16:57:50 -0600
parents 540e1940170f
children 633ca24d4d6e
files src/luan/lib/json/JsonToString.java src/luan/modules/Parsers.luan
diffstat 2 files changed, 74 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- a/src/luan/lib/json/JsonToString.java	Thu Aug 03 16:21:45 2017 -0600
+++ b/src/luan/lib/json/JsonToString.java	Thu Aug 03 16:57:50 2017 -0600
@@ -107,4 +107,74 @@
 		toString(entry.getValue(),sb);
 	}
 
+
+	public static String toPrettyString(Object obj) throws JsonException {
+		StringBuilder sb = new StringBuilder();
+		toString(obj,sb,0);
+		sb.append('\n');
+		return sb.toString();
+	}
+
+	private static void toString(Object obj,StringBuilder sb,int indented) throws JsonException {
+		if( obj instanceof List ) {
+			toString((List)obj,sb,indented);
+			return;
+		}
+		if( obj instanceof Map ) {
+			toString((Map)obj,sb,indented);
+			return;
+		}
+		toString(obj,sb);
+	}
+
+	private static void indent(StringBuilder sb,int indented) {
+		sb.append('\n');
+		for( int i=0; i<indented; i++ ) {
+			sb.append('\t');
+		}
+	}
+
+	private static void toString(List list,StringBuilder sb,int indented) {
+		if( list.isEmpty() ) {
+			sb.append("{}");
+			return;
+		}
+		sb.append('[');
+		indent(sb,indented+1);
+		toString(list.get(0),sb,indented+1);
+		for( int i=1; i<list.size(); i++ ) {
+			sb.append(',');
+			indent(sb,indented+1);
+			toString(list.get(i),sb,indented+1);
+		}
+		indent(sb,indented);
+		sb.append(']');
+		return;
+	}
+
+	private static void toString(Map map,StringBuilder sb,int indented) throws JsonException {
+		sb.append('{');
+		Iterator<Map.Entry> i = map.entrySet().iterator();
+		indent(sb,indented+1);
+		toString(i.next(),sb,indented+1);
+		while( i.hasNext() ) {
+			sb.append(',');
+			indent(sb,indented+1);
+			toString(i.next(),sb,indented+1);
+		}
+		indent(sb,indented);
+		sb.append('}');
+	}
+
+	private static void toString(Map.Entry entry,StringBuilder sb,int indented) throws JsonException {
+		Object key = entry.getKey();
+		if( !(key instanceof String) )
+			throw new JsonException("table keys must be strings");
+		toString((String)key,sb);
+		sb.append(": ");
+		toString(entry.getValue(),sb,indented);
+	}
+
+
+	private JsonToString() {}  // never
 }
--- a/src/luan/modules/Parsers.luan	Thu Aug 03 16:21:45 2017 -0600
+++ b/src/luan/modules/Parsers.luan	Thu Aug 03 16:57:50 2017 -0600
@@ -25,4 +25,8 @@
 	return JsonToString.toString(Luan.toJava(obj))
 end
 
+function Parsers.json_pretty_string(obj)
+	return JsonToString.toPrettyString(Luan.toJava(obj))
+end
+
 return Parsers