// (C) 2017 <>< Joshua Allen, Under MIT/x11 License. #define _GNU_SOURCE #include #include #include #include "json_helpers.h" #include #if !defined(__FreeBSD__) && !defined(__APPLE__) #include #endif #ifdef _MSC_VER #include // Windows doesn't provide asprintf, so we need to make it. int asprintf(char **strp, const char *fmt, ...) { char* buff = NULL; va_list listPointer; va_start( listPointer, fmt ); size_t lenNeeded = _vscprintf(fmt, listPointer) + 1; // add one for a terminating null if (lenNeeded > 1) { buff = (char*)malloc(lenNeeded); if (buff) { int bytesWritten = _vsnprintf(buff, lenNeeded, fmt, listPointer); if (bytesWritten < 0) { free(buff); buff = NULL; } } } if (strp) { *strp = buff; } return (int)lenNeeded; } #endif void json_write_float_array(FILE* f, const char* tag, float* v, uint8_t count) { uint8_t i = 0; char * str1 = NULL; char * str2 = NULL; if( asprintf(&str1,"\"%s\":[", tag) < 0 ) goto giveup; for (i=0;i=npos) return NULL; char* x = malloc(l); memcpy(x,str+start,l); x[l-1] = '\0'; return x; } static uint16_t json_load_array(const char* JSON_STRING, jsmntok_t* tokens, uint16_t size, char* tag) { jsmntok_t* t = tokens; uint16_t i = 0; char** values; values = alloca(sizeof(char*) * size); for (i=0;istart, t->end, JSON_STRING_LEN); } if (json_tag_value != NULL) json_tag_value(tag, values, (uint8_t)i); for (i=0;istart, tag_t->end, JSON_STRING_LEN); char* value = substr(JSON_STRING, value_t->start, value_t->end, JSON_STRING_LEN); if (value_t->type == JSMN_ARRAY) { i += json_load_array(JSON_STRING, tokens+i+2,value_t->size, tag); //look at array children } else if (value_t->type == JSMN_OBJECT) { if (json_begin_object != NULL) json_begin_object(tag); children = (int16_t)(value_t->size +1); //+1 to account for this loop where we are not yed parsing children // i += decode_jsmn_object(JSON_STRING, tokens+i+2,value_t->size); } else { if (json_tag_value != NULL) json_tag_value(tag, &value, 1); } if (children>=0) children--; if (children == 0) { children = -1; if (json_end_object!=NULL) json_end_object(); } // printf("%d %s \n", value_t->type, tag); free(tag); free(value); } free(tokens); free(JSON_STRING); } int parse_float_array(char* str, jsmntok_t* token, FLT** f, uint8_t count) { uint16_t i = 0; if (count==0) return 0; if (*f!=NULL) free(*f); *f = malloc(sizeof(FLT) * count); for(i=0;iend; char* s = str+token->start; #ifdef USE_DOUBLE (*f)[i] = strtod(s, &end); #else (*f)[i] = strtof(s, &end); #endif if (s == end) { free(*f); *f=NULL; return 0; //not a float } token++; } return count; }