Browse Source

Add unit test for array of objs

PUBLISHED_FROM=7cd23eb46d1400e0b75f5f088bc104c048d2b1cf
Sergey Lyubka 9 years ago
parent
commit
83620e9cd1
4 changed files with 35 additions and 0 deletions
  1. 1 0
      docs/examples/intro.md
  2. 17 0
      docs/examples/json_scanf2.md
  3. BIN
      unit_test
  4. 17 0
      unit_test.c

+ 1 - 0
docs/examples/intro.md

@@ -3,4 +3,5 @@ title: Examples
 items:
   - { name: json_scanf.md }
   - { name: json_printf.md }
+  - { name: json_scanf2.md }
 ---

+ 17 - 0
docs/examples/json_scanf2.md

@@ -0,0 +1,17 @@
+---
+title: json_scanf() complex array
+---
+
+```c
+  // str has the following JSON string - array of objects:
+  // { "a": [ {"b": 123}, {"b": 345} ] }
+  // This example shows how to iterate over array, and parse each object.
+
+  int i, value, len = strlen(str);
+  struct json_token t;
+
+  for (i = 0; json_scanf_array_elem(str, len, ".a", i, &t) > 0; i++) {
+    // t.type == JSON_TYPE_OBJECT
+    json_scanf(t.ptr, t.len, "{b: %d}", &value);  // value is 123, then 345
+  }
+```

BIN
unit_test


+ 17 - 0
unit_test.c

@@ -367,6 +367,23 @@ static const char *test_scanf(void) {
     ASSERT(n == 1);
   }
 
+  {
+    /* Test array of objects */
+    const char *str = " { \"a\": [ {\"b\": 123}, {\"b\": 345} ]} ";
+    int i, value, len = strlen(str), values[] = {123, 345};
+    struct json_token t;
+
+    /* Scan each array element into a token */
+    for (i = 0; json_scanf_array_elem(str, len, ".a", i, &t) > 0; i++) {
+      /* Now scan each token */
+      ASSERT(t.type == JSON_TYPE_OBJECT);
+      ASSERT(json_scanf(t.ptr, t.len, "{b: %d}", &value) == 1);
+      ASSERT((size_t) i < sizeof(values) / sizeof(values[0]));
+      ASSERT(values[i] == value);
+    }
+    ASSERT(i == 2);
+  }
+
   return NULL;
 }