Browse Source

JSON array as a valid first input not only object.

Allow to parse JSON which starts with an array that is first character
in JSON data is '['.

*Example* :
`[80, 443, {x: 25} ]`
Access the 'x' value using path `[2].x`
w-vi 10 years ago
parent
commit
1f5101a35e
2 changed files with 20 additions and 2 deletions
  1. 17 1
      frozen.c
  2. 3 1
      unit_test.c

+ 17 - 1
frozen.c

@@ -76,6 +76,12 @@ static int test_and_skip(struct frozen *f, int expected) {
   return ch == END_OF_STRING ? JSON_STRING_INCOMPLETE : JSON_STRING_INVALID;
 }
 
+static int test_no_skip(struct frozen *f, int expected) {
+  int ch = cur(f);
+  if (ch == expected) { return 0; }
+  return ch == END_OF_STRING ? JSON_STRING_INCOMPLETE : JSON_STRING_INVALID;
+}
+
 static int is_alpha(int ch) {
   return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z');
 }
@@ -292,9 +298,19 @@ static int parse_object(struct frozen *f) {
 }
 
 static int doit(struct frozen *f) {
+  int ret = 0;
+    
   if (f->cur == 0 || f->end < f->cur) return JSON_STRING_INVALID;
   if (f->end == f->cur) return JSON_STRING_INCOMPLETE;
-  TRY(parse_object(f));
+
+  if (0 == (ret = test_no_skip(f, '{'))) {
+      TRY(parse_object(f));
+  } else if (0 == (ret = test_no_skip(f, '['))) {
+      TRY(parse_array(f));
+  } else {
+      return ret;
+  }
+  
   TRY(capture_ptr(f, f->cur, JSON_TYPE_EOF));
   capture_len(f, f->num_tokens, f->cur);
   return 0;

+ 3 - 1
unit_test.c

@@ -48,7 +48,7 @@
 
 static int static_num_tests = 0;
 
-static int cmp_token(const struct json_token *tok, const char *str, int type) {
+static int cmp_token(const struct json_token *tok, const char *str, enum json_type type) {
 #if 0
   printf("[%.*s] [%s]\n", tok->len, tok->ptr, str);
 #endif
@@ -92,6 +92,8 @@ static const char *test_errors(void) {
     { "{a:1,b:2} xxxx", 9 },
     { "{a:1,b:{},c:[{}]} xxxx", 17 },
     { "{a:true,b:[false,null]} xxxx", 23 },
+    { "[1.23, 3, 5]", 12 },
+    { "[13, {\"a\":\"hi there\"}, 5]", 25 },
     { NULL, 0 }
   };
   const char *s1 = " { a: 1, b: \"hi there\", c: true, d: false, "