123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293 |
- #include <stdio.h>
- #include <stdlib.h>
- #include "json.h"
- int parse(){
- char str[200];
- char* key = NULL;
- char* val = NULL;
- JsonParser json;
- strcpy(str, "{\"name\" : \"Jack\", \"age\": 27, \"test\": true, \"tab\": [1, 2, 3, 4, 5], \"obj\": {\"name\" : \"Jack\", \"age\": 27}, \"nb\": 27.8 }");
- //Parse
- int a = json_parse(&json, str);
- printf("Parse : %d\n", a);
- //Affiche toutes les clefs : valeurs
- for(int i = 0; i < json.elt; i++){
- key = key_index(&json, i);
- val = get_index(&json, i);
- printf("%s : %s\n", key, val);
- }
- //Recup un nombre
- printf("Double : %f %.2f | Int : %d %d\n", get_number(&json, "age"), get_number(&json, "nb"), get_integer(&json, "age"), get_integer(&json, "nb"));
- //Recup boolean
- printf("Bool : %d %d\n", get_boolean(&json, "test"), get_boolean(&json, "tab"));
- //Recup obj
- JsonParser* js;
- js = get_object(&json, "obj");
- if(js != NULL){
- int key_i = get_pos(js, "name");
- printf("JSON : %s %s, age %d\n", key_index(js, key_i), get_value(js, "name"), get_integer(js, "age"));
- } else {
- printf("JSON : Error");
- }
- //Supprime
- free(key);
- free(val);
- clean_json_parser(&json);
- return 0;
- }
- int encode(){
- //Encode
- JsonEncoder json;
- ini_encoder(&json);
- add_string(&json, "name", "robert");
- add_number(&json, "nb", 25.698, 2);
- add_integer(&json, "int", 846);
- add_string(&json, "aze", "rty");
- add_boolean(&json, "bool", false);
- add_value(&json, "\"test\": \"aze\nrty\"");
- printf("Json\n");
- printf("%s\n", json_encode(&json));
-
- //Encode un JsonEncoder
- JsonEncoder json2;
- ini_encoder(&json2);
- add_integer(&json2, "vie", 42);
- add_object(&json2, "obj", json);
- printf("\nJson 2\n");
- printf("%s\n", json_encode(&json2));
-
- //Decode
- JsonParser parser, *parser2;
- char* key, *val;
- json_parse(&parser, json_encode(&json2));
- //Affiche toutes les clefs : valeurs
- printf("\nParser\n");
- for(int i = 0; i < parser.elt; i++){
- key = key_index(&parser, i);
- val = get_index(&parser, i);
- printf("%s : %s\n", key, val);
- }
- //Lecture du sous json
- parser2 = get_object(&parser, "obj");
- //Affiche toutes les clefs : valeurs
- printf("\nParser 2\n");
- for(int i = 0; i < parser2->elt; i++){
- key = key_index(parser2, i);
- val = get_index(parser2, i);
- printf("%s : %s\n", key, val);
- }
-
- //Clean
- clean_json_encoder(&json);
- clean_json_encoder(&json2);
- clean_json_parser(&parser);
-
- return 0;
- }
- int main(){
- //return parse();
- return encode();
- }
|