Skip to content

Commit 1945ecb

Browse files
authored
Added line comment support, BOM stripping, empty key support
Added support for // line comments at the end of a line. This can be disabled by the static "allowLineComments" setting. Explicitly stripping the BOM (Byte Order Mark) character Allowing the empty string "" as key.
1 parent 7f085a4 commit 1945ecb

File tree

1 file changed

+23
-2
lines changed

1 file changed

+23
-2
lines changed

SimpleJSON.cs

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -88,11 +88,21 @@
8888
*
8989
* [2018-04-25 Update]
9090
* - Added support for parsing single values (JSONBool, JSONString, JSONNumber, JSONNull) as top level value.
91-
*
91+
*
9292
* [2019-02-18 Update]
9393
* - Added HasKey(key) and GetValueOrDefault(key, default) to the JSONNode class to provide way to read
9494
* values conditionally without creating a LazyCreator
9595
*
96+
* [2019-03-25 Update]
97+
* - Added static setting "allowLineComments" to the JSONNode class which is true by default. This allows
98+
* "//" line comments when parsing json text as long as it's not within quoted text. All text after // up
99+
* to the end of the line is completely ignored / skipped. This makes it easier to create human readable
100+
* and editable files. Note that stripped comments are not read, processed or preserved in any way. So
101+
* this feature is only relevant for human created files.
102+
* - Explicitly strip BOM (Byte Order Mark) when parsing to avoid getting it leaked into a single primitive
103+
* value. That's a rare case but better safe than sorry.
104+
* - Allowing adding the empty string as key
105+
*
96106
* The MIT License (MIT)
97107
*
98108
* Copyright (c) 2012-2017 Markus Göbel (Bunny83)
@@ -247,6 +257,7 @@ IEnumerator IEnumerable.GetEnumerator()
247257

248258
public static bool forceASCII = false; // Use Unicode by default
249259
public static bool longAsString = false; // lazy creator creates a JSONString instead of JSONNumber
260+
public static bool allowLineComments = true; // allow "//"-style comments at the end of a line
250261

251262
public abstract JSONNodeType Tag { get; }
252263

@@ -727,6 +738,16 @@ public static JSONNode Parse(string aJSON)
727738
}
728739
}
729740
break;
741+
case '/':
742+
if (allowLineComments && !QuoteMode && i + 1 < aJSON.Length && aJSON[i+1] == '/')
743+
{
744+
while (++i < aJSON.Length && aJSON[i] != '\n' && aJSON[i] != '\r') ;
745+
break;
746+
}
747+
Token.Append(aJSON[i]);
748+
break;
749+
case '\uFEFF': // remove / ignore BOM (Byte Order Mark)
750+
break;
730751

731752
default:
732753
Token.Append(aJSON[i]);
@@ -917,7 +938,7 @@ public override void Add(string aKey, JSONNode aItem)
917938
if (aItem == null)
918939
aItem = JSONNull.CreateOrGet();
919940

920-
if (!string.IsNullOrEmpty(aKey))
941+
if (aKey != null)
921942
{
922943
if (m_Dict.ContainsKey(aKey))
923944
m_Dict[aKey] = aItem;

0 commit comments

Comments
 (0)