Skip to content

Commit 1c89f3b

Browse files
committed
JAVA-319: improve JSON parser to not require quotes around keys
1 parent a3d885a commit 1c89f3b

File tree

1 file changed

+20
-11
lines changed

1 file changed

+20
-11
lines changed

src/main/com/mongodb/util/JSON.java

Lines changed: 20 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -348,7 +348,7 @@ protected Object parse(String name) {
348348
// string
349349
case '\'':
350350
case '\"':
351-
value = parseString();
351+
value = parseString(true);
352352
break;
353353
// number
354354
case '0': case '1': case '2': case '3': case '4': case '5':
@@ -395,7 +395,7 @@ protected Object parseObject(String name){
395395
read('{');
396396
char current = get();
397397
while(get() != '}') {
398-
String key = parseString();
398+
String key = parseString(false);
399399
read(':');
400400
Object value = parse(key);
401401
doCallback(key, value);
@@ -505,22 +505,31 @@ public char get() {
505505
* @return the next string.
506506
* @throws JSONParseException if invalid JSON is found
507507
*/
508-
public String parseString() {
509-
char quot;
508+
public String parseString(boolean needQuote) {
509+
char quot = 0;
510510
if(check('\''))
511511
quot = '\'';
512512
else if(check('\"'))
513513
quot = '\"';
514-
else
514+
else if (needQuote)
515515
throw new JSONParseException(s, pos);
516516

517517
char current;
518518

519-
read(quot);
519+
if (quot > 0)
520+
read(quot);
520521
StringBuilder buf = new StringBuilder();
521522
int start = pos;
522-
while(pos < s.length() &&
523-
(current = s.charAt(pos)) != quot) {
523+
while(pos < s.length()) {
524+
current = s.charAt(pos);
525+
if (quot > 0) {
526+
if (current == quot)
527+
break;
528+
} else {
529+
if (current == ':' || current == ' ')
530+
break;
531+
}
532+
524533
if(current == '\\') {
525534
pos++;
526535

@@ -565,9 +574,9 @@ else if(check('\"'))
565574
}
566575
pos++;
567576
}
568-
read(quot);
569-
570-
buf.append(s.substring(start, pos-1));
577+
buf.append(s.substring(start, pos));
578+
if (quot > 0)
579+
read(quot);
571580
return buf.toString();
572581
}
573582

0 commit comments

Comments
 (0)