| 1 | #define CTEST_MAIN |
| 2 | #include "ctest.h" |
| 3 | #include "common.h" |
| 4 | #include "vws.h" |
| 5 | #include "util/yyjson.h" |
| 6 | |
| 7 | #pragma GCC diagnostic push |
| 8 | #pragma GCC diagnostic ignored "-Wunused-parameter" |
| 9 | #pragma clang diagnostic push |
| 10 | #pragma clang diagnostic ignored "-Wunused-parameter" |
| 11 | |
| 12 | CTEST_DATA(test) |
| 13 | { |
| 14 | unsigned char* buffer; |
| 15 | }; |
| 16 | |
| 17 | CTEST_SETUP(test) |
| 18 | { |
| 19 | data->buffer = (unsigned char*)malloc(1024); |
| 20 | } |
| 21 | |
| 22 | CTEST_TEARDOWN(test) |
| 23 | { |
| 24 | if (data->buffer) |
| 25 | { |
| 26 | free(data->buffer); |
| 27 | } |
| 28 | } |
| 29 | |
| 30 | CTEST2(test, read) |
| 31 | { |
| 32 | const char *json = "{\"name\":\"Mash\",\"star\":4,\"hits\":[2,2,1,3]}" ; |
| 33 | |
| 34 | // Read JSON and get root |
| 35 | yyjson_doc* doc = yyjson_read(json, strlen(json), 0); |
| 36 | yyjson_val* root = yyjson_doc_get_root(doc); |
| 37 | |
| 38 | // Get root["name"] |
| 39 | yyjson_val* name = yyjson_obj_get(root, "name" ); |
| 40 | |
| 41 | ASSERT_TRUE(yyjson_get_type(root) == YYJSON_TYPE_OBJ); |
| 42 | |
| 43 | printf("name: %s\n" , yyjson_get_str(name)); |
| 44 | printf("name length:%d\n" , (int)yyjson_get_len(name)); |
| 45 | |
| 46 | // Get root["star"] |
| 47 | yyjson_val *star = yyjson_obj_get(root, "star" ); |
| 48 | printf("star: %d\n" , (int)yyjson_get_int(star)); |
| 49 | |
| 50 | // Get root["hits"], iterate over the array |
| 51 | yyjson_val *hits = yyjson_obj_get(root, "hits" ); |
| 52 | size_t idx, max; |
| 53 | yyjson_val *hit; |
| 54 | yyjson_arr_foreach(hits, idx, max, hit) |
| 55 | { |
| 56 | printf("hit%d: %d\n" , (int)idx, (int)yyjson_get_int(hit)); |
| 57 | } |
| 58 | |
| 59 | // Free the doc |
| 60 | yyjson_doc_free(doc); |
| 61 | } |
| 62 | |
| 63 | CTEST2(test, write) |
| 64 | { |
| 65 | // Create a mutable doc |
| 66 | yyjson_mut_doc* doc = yyjson_mut_doc_new(NULL); |
| 67 | yyjson_mut_val* root = yyjson_mut_obj(doc); |
| 68 | yyjson_mut_doc_set_root(doc, root); |
| 69 | |
| 70 | // Set root["name"] and root["star"] |
| 71 | yyjson_mut_obj_add_str(doc, root, "name" , "Mash" ); |
| 72 | yyjson_mut_obj_add_int(doc, root, "star" , 4); |
| 73 | |
| 74 | // Set root["hits"] with an array |
| 75 | int hits_arr[] = {2, 2, 1, 3}; |
| 76 | yyjson_mut_val* hits = yyjson_mut_arr_with_sint32(doc, hits_arr, 4); |
| 77 | yyjson_mut_obj_add_val(doc, root, "hits" , hits); |
| 78 | |
| 79 | // To string, minified |
| 80 | cstr json = yyjson_mut_write(doc, 0, NULL); |
| 81 | |
| 82 | if (json) |
| 83 | { |
| 84 | printf("json: %s\n" , json); // {"name":"Mash","star":4,"hits":[2,2,1,3]} |
| 85 | free((void *)json); |
| 86 | } |
| 87 | |
| 88 | // Free the doc |
| 89 | yyjson_mut_doc_free(doc); |
| 90 | } |
| 91 | |
| 92 | int main(int argc, cstr argv[]) |
| 93 | { |
| 94 | return ctest_main(argc, argv); |
| 95 | } |
| 96 | |
| 97 | #pragma GCC diagnostic pop |
| 98 | #pragma clang diagnostic pop |
| 99 | |