diff --git a/Json5.Tests/Stringifying/ObjectTests.cs b/Json5.Tests/Stringifying/ObjectTests.cs index 5b54d75..99eaa6b 100644 --- a/Json5.Tests/Stringifying/ObjectTests.cs +++ b/Json5.Tests/Stringifying/ObjectTests.cs @@ -22,7 +22,7 @@ public void UnquotedPropertyNamesTest() [TestMethod] public void SingleQuotedStringPropertyNamesTest() { - var s = Json5.Stringify(new Json5Object { { "a-b", 1 } }); + var s = Json5.Stringify(new Json5Object { { "'a-b'", 1 } }); Assert.AreEqual("{'a-b':1}", s); } diff --git a/Json5/Json5.cs b/Json5/Json5.cs index df588b5..99a739c 100644 --- a/Json5/Json5.cs +++ b/Json5/Json5.cs @@ -125,19 +125,30 @@ private static Json5Value Walk(Json5Container holder, string key, Func= singleQuotes ? '\'' : '"'; + char quote = doubleQuotes >= singleQuotes ? singleQuote : doubleQuote; + + // Hack that handles single quoted strings (e.g. 'a-b') by removing the single quotes from start and end + if (s != null && s.Length > 1 && s[0] == singleQuote && s[s.Length - 1] == singleQuote) + { + quote = singleQuote; + s = s.Substring(1, s.Length - 2); + } + return quote + EscapeString(s, quote) + quote; } diff --git a/Json5/Json5Object.cs b/Json5/Json5Object.cs index 36ac71b..33b9763 100644 --- a/Json5/Json5Object.cs +++ b/Json5/Json5Object.cs @@ -124,9 +124,39 @@ private string KeyToString(string key) // 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 (DoesIdentifierNeedDoubleQuotes(key)) + { + return Json5.QuoteString(key); + } + return key; + } return Json5.QuoteString(key); } + + /// + /// Does the identifier need extra double quotes, Currently used to check if there would be issue with single quotes + /// + /// String to check + /// True if needs; False otherwise + private static bool DoesIdentifierNeedDoubleQuotes(string input) + { + // If input contains single quotes that do not start and end the input, then it needs double quotes + if (input.Contains("'")) + { + // If it starts and ends with single quote, everything is OK + if (input[0] == '\'' && input[input.Length - 1] == '\'') + { + return false; + } + + // Otherwise it need double quotes + return true; + } + + return false; + } } }