changeset 1307:6c8ceca4a10b

json fixes
author Franklin Schmidt <fschmidt@gmail.com>
date Wed, 23 Jan 2019 13:34:18 -0700
parents 97e7c25e9e70
children 70eecde81820
files src/luan/lib/json/JsonParser.java src/luan/lib/json/JsonToString.java src/luan/modules/Html.luan
diffstat 3 files changed, 37 insertions(+), 13 deletions(-) [+]
line wrap: on
line diff
--- a/src/luan/lib/json/JsonParser.java	Wed Jan 23 12:48:47 2019 -0700
+++ b/src/luan/lib/json/JsonParser.java	Wed Jan 23 13:34:18 2019 -0700
@@ -71,6 +71,7 @@
 					c = parser.lastChar();
 					switch(c) {
 					case '"':
+					case '\'':  // not in spec
 					case '\\':
 					case '/':
 						sb.append(c);
--- a/src/luan/lib/json/JsonToString.java	Wed Jan 23 12:48:47 2019 -0700
+++ b/src/luan/lib/json/JsonToString.java	Wed Jan 23 13:34:18 2019 -0700
@@ -29,12 +29,6 @@
 		return sb.toString();
 	}
 
-	public static String encodeString(String s) {
-		StringBuilder sb = new StringBuilder();
-		encodeString(s,sb);
-		return sb.toString();
-	}
-
 	private void toString(Object obj,StringBuilder sb,int indented) throws JsonException {
 		if( obj == null || obj instanceof Boolean || obj instanceof Number ) {
 			sb.append(obj);
@@ -57,18 +51,46 @@
 
 	private static void toString(final String s,StringBuilder sb) {
 		sb.append('"');
-		encodeString(s,sb);
-		sb.append('"');
-	}
-
-	private static void encodeString(final String s,StringBuilder sb) {
 		for( int i=0; i<s.length(); i++ ) {
 			char c = s.charAt(i);
 			switch(c) {
 			case '"':
 				sb.append("\\\"");
 				break;
-			case '\'':
+			case '\\':
+				sb.append("\\\\");
+				break;
+			case '\b':
+				sb.append("\\b");
+				break;
+			case '\f':
+				sb.append("\\f");
+				break;
+			case '\n':
+				sb.append("\\n");
+				break;
+			case '\r':
+				sb.append("\\r");
+				break;
+			case '\t':
+				sb.append("\\t");
+				break;
+			default:
+				sb.append(c);
+			}
+		}
+		sb.append('"');
+	}
+
+	public static String javascriptEncode(String s) {
+		StringBuilder sb = new StringBuilder();
+		for( int i=0; i<s.length(); i++ ) {
+			char c = s.charAt(i);
+			switch(c) {
+			case '"':
+				sb.append("\\\"");
+				break;
+			case '\'':  // added for javascript
 				sb.append("\\'");
 				break;
 			case '\\':
@@ -93,6 +115,7 @@
 				sb.append(c);
 			}
 		}
+		return sb.toString();
 	}
 
 	private void toString(List list,StringBuilder sb,int indented) {
--- a/src/luan/modules/Html.luan	Wed Jan 23 12:48:47 2019 -0700
+++ b/src/luan/modules/Html.luan	Wed Jan 23 13:34:18 2019 -0700
@@ -15,7 +15,7 @@
 local Html = {}
 
 Html.encode = HtmlLuan.encode
-Html.javascript_encode = JsonToString.encodeString
+Html.javascript_encode = JsonToString.javascriptEncode
 
 local quote = HtmlLuan.quote
 Html.quote = quote