Browse Source

:sparkles: Recuperation nom clef

Arthur Brandao 6 years ago
parent
commit
b1a3ddf639
3 changed files with 36 additions and 21 deletions
  1. 3 2
      Serveur/json.h
  2. 28 14
      Serveur/json_parser.c
  3. 5 5
      Serveur/main.c

+ 3 - 2
Serveur/json.h

@@ -33,10 +33,11 @@ typedef struct{
 
 /* --- fonctions ---- */
 int json_parse(JsonParser*, char*);
-void clean_json_parser(JsonParser*);
+char* key_index(JsonParser*, int);
+char* get_index(JsonParser*, int);
 int get_type(JsonParser*, char*);
 char* get(JsonParser*, char*);
-char* get_index(JsonParser*, int);
+void clean_json_parser(JsonParser*);
 
 #endif /* JSON_H */
 

+ 28 - 14
Serveur/json_parser.c

@@ -232,22 +232,18 @@ int json_parse(JsonParser* this, char* json) {
     return JSON_OK;
 }
 
-int get_type(JsonParser* this, char* key){
-    //Recup index
-    int index;
-    if((index = search_index(this, key)) == JSON_ERROR){
-        return JSON_ERROR;
-    }
-    return this->type[index];
-}
-
-char* get(JsonParser* this, char* key){
-    //Recup index
-    int index;
-    if((index = search_index(this, key)) == JSON_ERROR){
+char* key_index(JsonParser* this, int index){
+    //Index incorrect
+    if(index < 0 || index >= this->elt){
         return NULL;
     }
-    return get_index(this, index);
+    //Creation string d'accueil
+    char* val;
+    val = malloc(this->key_length[index] * sizeof(char));
+    //Copie valeur
+    strncpy(val, this->key[index], this->key_length[index]);
+    //Retour
+    return val;
 }
 
 char* get_index(JsonParser* this, int index){
@@ -264,6 +260,24 @@ char* get_index(JsonParser* this, int index){
     return val;
 }
 
+int get_type(JsonParser* this, char* key){
+    //Recup index
+    int index;
+    if((index = search_index(this, key)) == JSON_ERROR){
+        return JSON_ERROR;
+    }
+    return this->type[index];
+}
+
+char* get(JsonParser* this, char* key){
+    //Recup index
+    int index;
+    if((index = search_index(this, key)) == JSON_ERROR){
+        return NULL;
+    }
+    return get_index(this, index);
+}
+
 void clean_json_parser(JsonParser* this) {
     free(this->key);
     free(this->key_length);

+ 5 - 5
Serveur/main.c

@@ -4,21 +4,21 @@
 
 int main(){
     char str[200];
-    char key[100];
-    char* val;
+    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}, \"age\": 27.8 }");
     int a = json_parse(&json, str);
     printf("\nParse : %d\n", a);
     
     for(int i = 0; i < json.elt; i++){
-        memset(key, 0, 100);
-        strncpy(key, json.key[i], json.key_length[i]);
+        key = key_index(&json, i);
         val = get_index(&json, i);
         printf("%s : %s\n", key, val);
         //printf("%d %d\n", json.key_length[i], json.val_length[i]);
     }
-    
+    free(key);
+    free(val);
     clean_json_parser(&json);
     return 0;
 }