|
| 1 | +#include <stdio.h> |
| 2 | +#include <stdlib.h> |
| 3 | +#include <string.h> |
| 4 | +#include "js0n.h" |
| 5 | +#include "j0g.h" |
| 6 | + |
| 7 | +// dumbed down parser, expects null terminated json, if fails the *index is 0 (and safe to pass into j0g_*) |
| 8 | +char *j0g(char *json, unsigned short *index, int ilen) |
| 9 | +{ |
| 10 | + int ret, len; |
| 11 | + if(!json) return NULL; |
| 12 | + len = strlen(json); |
| 13 | + ret = js0n((unsigned char*)json, len, index, ilen); |
| 14 | + if(ret) *index = 0; |
| 15 | + return json; |
| 16 | +} |
| 17 | + |
| 18 | +// return the null-terminated string value matching the given key |
| 19 | +char *j0g_str(char *key, char *json, unsigned short *index) |
| 20 | +{ |
| 21 | + char *str, *cursor; |
| 22 | + int val = j0g_val(key, json, index); |
| 23 | + if(!val) return NULL; |
| 24 | + *(json+(index[val]+index[val+1])) = 0; // null terminate |
| 25 | + // unescape stuff |
| 26 | + for(cursor=str=json+index[val]; *cursor; cursor++,str++) |
| 27 | + { |
| 28 | + if(*cursor == '\\' && *(cursor+1) == 'n') |
| 29 | + { |
| 30 | + *str = '\n'; |
| 31 | + cursor++; |
| 32 | + }else if(*cursor == '\\' && *(cursor+1) == '"'){ |
| 33 | + *str = '"'; |
| 34 | + cursor++; |
| 35 | + }else{ |
| 36 | + *str = *cursor; |
| 37 | + } |
| 38 | + } |
| 39 | + *str = *cursor; // copy null terminator too |
| 40 | + return (char*)json+index[val]; |
| 41 | +} |
| 42 | + |
| 43 | +// return 1 if the value is the bool value true, number 1, or even the string "true", false otherwise |
| 44 | +int j0g_test(char *key, char *json, unsigned short *index) |
| 45 | +{ |
| 46 | + char *val = j0g_str(key, json, index); |
| 47 | + if(!val) return 0; |
| 48 | + if(strcmp(val, "true") == 0) return 1; |
| 49 | + if(strcmp(val, "1") == 0) return 1; |
| 50 | + return 0; |
| 51 | +} |
| 52 | + |
| 53 | +// return the index offset of the value matching the given key |
| 54 | +int j0g_val(char *key, char *json, unsigned short *index) |
| 55 | +{ |
| 56 | + if(!key || !json) return 0; |
| 57 | + int i, klen = strlen(key); |
| 58 | + for(i=0;index[i];i+=4) |
| 59 | + { |
| 60 | + if(klen == index[i+1] && strncmp(key,(char*)json+index[i],klen) == 0) return i+2; |
| 61 | + } |
| 62 | + return 0; |
| 63 | +} |
| 64 | + |
0 commit comments