#include #include #include #include #include "init.h" #include "json.h" #include "valloc.h" #define READ_FILE "test/file/read.json" #define WRITE_FILE "test/file/write.json" static void test_read(void) { json_t root = NULL, x = NULL; char *s = NULL; root = json_file_load(WRITE_FILE); if (!root) { int type = 0, line = 0, column = 0; type = json_error_info(&line, &column); printf("error at line %d column %d type %d.\r\n", line, column, type); return; } printf("load success!\r\n"); x = json_to_key(root, "version"); if (x) { if (json_isstring(x)) printf("%s\r\n", json_value_string(x)); } x = json_to_index(root, 5, 0); printf("x type %d, %d\r\n", json_type(x), json_value_int(x)); s = json_dumps(root, 0, 0, NULL); printf("%s\r\n", s); if (s) free(s); /* dump json file */ // json_file_dump(root, WRITE_FILE); json_delete(root); } static void test_write(void) { json_t json, t, j; int aa[10] = {0,1,2,3,4,5,6,7,8,9}; char *s; /* 创建根结点 */ json = json_create(); json_set_object(json, NULL); /* 向根节点尾部插入string和int型的两个键值对 */ json_add_string_to_object(json, "name", "Lisi"); json_set_array_int(json_add_null_to_object(json, "table"), aa, 10); json_add_null_to_object(json, "null"); json_add_true_to_object(json, "true"); json_add_false_to_object(json, "false"); json_add_bool_to_object(json, "bool", JSON_TRUE); json_add_int_to_object(json, "int", 178); json_add_float_to_object(json, "float", 12.3333); json_add_string_to_object(json, "string", "18"); json_add_null_to_object(json, "array"); json_add_null_to_object(json, "object"); json_add_array_to_object(json, "数组"); json_attach(json, 3, json_create_float_for_object("pi", 3.14159)); json_add_null_to_array(t); json_add_true_to_array(t); json_add_false_to_array(t); json_add_bool_to_array(t, JSON_TRUE); json_add_int_to_array(t, 178); json_add_float_to_array(t, 12.340000); json_add_string_to_array(t, "18"); json_attach(t, 3, json_create_string_for_array("pi")); json_erase_by_index(t, 8); json_erase_by_key(json, "bool"); /* get */ t = json_to_key(json, "int"); if (json_isint(t)) printf("%d\r\n", json_value_int(t)); /* array */ t = json_to_key(json, "array"); json_set_array(t, NULL); json_add_null_to_array(t); json_add_true_to_array(t); json_add_false_to_array(t); json_attach(t, json_size(t), json_set_array(json_create(), NULL)); /* object */ t = json_to_key(json, "object"); json_set_object(t, NULL); json_add_false_to_object(t, "1"); json_add_int_to_object(t, "2", 15); /* preview json */ s = json_dumps(json, 0, 0, NULL); printf("%s\r\n", s); if (s) free(s); /* dump json file */ json_file_dump(json, WRITE_FILE); json_delete(json); } static void test(void) { printf("json test!\r\n"); test_write(); // test_read(); v_check_unfree(); } init_export_app(test);