diff --git a/Json5/Json5.cs b/Json5/Json5.cs index df588b5..5bfb46c 100644 --- a/Json5/Json5.cs +++ b/Json5/Json5.cs @@ -157,16 +157,23 @@ private static string EscapeChar(char c, char quote) switch (c) { + case '\0': return "\\0"; case '\b': return "\\b"; case '\t': return "\\t"; case '\n': return "\\n"; case '\f': return "\\f"; case '\r': return "\\r"; + case '\v': return "\\v"; case '\\': return "\\\\"; case '\u2028': return "\\u2028"; case '\u2029': return "\\u2029"; } + if (c < ' ') + { + return "\\x" + ((int)c).ToString("x2"); + } + switch (char.GetUnicodeCategory(c)) { case UnicodeCategory.Control: @@ -176,11 +183,7 @@ private static string EscapeChar(char c, char quote) case UnicodeCategory.OtherNotAssigned: return "\\u" + ((int)c).ToString("x4"); } - - // // Node does this. - //if(c <= 31) - // return "\\u" + ((int)c).ToString("x4"); - + return c.ToString(); } } diff --git a/Json5/Json5Object.cs b/Json5/Json5Object.cs index 36ac71b..422eaf9 100644 --- a/Json5/Json5Object.cs +++ b/Json5/Json5Object.cs @@ -3,6 +3,7 @@ namespace Json5 { using Parsing; + using System.Text.RegularExpressions; public class Json5Object : Json5Container, IEnumerable> { @@ -105,25 +106,18 @@ internal override string ToJson5String(string space, string indent, bool useOneS return s; } + // https://www.ecma-international.org/ecma-262/5.1/ + // Match IdentifierName (except escapes) + private static Regex identifierNameRegex = new Regex(@" + ^ + [\$_\p{L}\p{Nl}] + [\$_\p{L}\p{Nl}\p{Mn}\p{Mc}\p{Nd}\p{Pc}\u200c\u200d]* + $ + ", RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled); + private string KeyToString(string key) { - if (key.Length == 0) - return "''"; - - - // TODO: Create a Utility class for interally used methods. - - //if(char.IsLetter(key[0]) || char.GetUnicodeCategory(key[0]) == System.Globalization.UnicodeCategory.LetterNumber) - //{ - // for(int i = 1; i < key.Length; i++) - // { - - // } - //} - - // This will not always work unless we check for Eof after the Identifier. - // We should probably handle this another way. - if (new Json5Lexer(key).Read().Type == Json5TokenType.Identifier) + if (identifierNameRegex.IsMatch(key)) return key; return Json5.QuoteString(key);