kit

kit
git clone https://git.ryansepassi.com/git/kit.git
Log | Files | Refs | README

use_yyjson.c (1468B)


      1 /* use_yyjson.c — exercise yyjson read / navigate / mutate / write.
      2  * Deterministic output. (Gate is KNOWN-RED: kit miscompiles yyjson.c today.) */
      3 #include "yyjson.h"
      4 #include <stdio.h>
      5 #include <string.h>
      6 
      7 int main(void) {
      8   const char *json =
      9       "{\"name\":\"kit\",\"n\":42,\"arr\":[10,20,30],\"nested\":{\"ok\":true}}";
     10 
     11   yyjson_doc *doc = yyjson_read(json, strlen(json), 0);
     12   if (!doc) {
     13     printf("read-fail\n");
     14     return 1;
     15   }
     16   yyjson_val *root = yyjson_doc_get_root(doc);
     17   printf("name=%s n=%lld arrlen=%zu\n",
     18          yyjson_get_str(yyjson_obj_get(root, "name")),
     19          (long long)yyjson_get_sint(yyjson_obj_get(root, "n")),
     20          yyjson_arr_size(yyjson_obj_get(root, "arr")));
     21 
     22   long long sum = 0;
     23   yyjson_val *arr = yyjson_obj_get(root, "arr");
     24   size_t idx, max;
     25   yyjson_val *v;
     26   yyjson_arr_foreach(arr, idx, max, v) sum += yyjson_get_sint(v);
     27   printf("arr-sum=%lld nested-ok=%d\n", sum,
     28          yyjson_get_bool(yyjson_obj_get(yyjson_obj_get(root, "nested"), "ok")));
     29 
     30   /* Build a mutable doc and serialize it. */
     31   yyjson_mut_doc *mdoc = yyjson_mut_doc_new(NULL);
     32   yyjson_mut_val *obj = yyjson_mut_obj(mdoc);
     33   yyjson_mut_doc_set_root(mdoc, obj);
     34   yyjson_mut_obj_add_str(mdoc, obj, "lib", "yyjson");
     35   yyjson_mut_obj_add_int(mdoc, obj, "answer", 42);
     36   char *out = yyjson_mut_write(mdoc, 0, NULL);
     37   printf("built=%s\n", out ? out : "(null)");
     38 
     39   free(out);
     40   yyjson_mut_doc_free(mdoc);
     41   yyjson_doc_free(doc);
     42   return 0;
     43 }