stat_t set_defaults(nvObj_t *nv) { // failsafe. nv->value must be true or no action occurs if (fp_FALSE(nv->value)) return(help_defa(nv)); _set_defa(nv); // The values in nv are now garbage. Mark the nv as $defa so it displays nicely. // strncpy(nv->token, "defa", TOKEN_LEN); // correct, but not required // nv->index = nv_get_index("", nv->token); // correct, but not required nv->valuetype = TYPE_INTEGER; nv->value = 1; return (STAT_OK); }
uint16_t json_serialize(nvObj_t *nv, char *out_buf, uint16_t size) { #ifdef __SILENCE_JSON_RESPONSES return (0); #else char *str = out_buf; char *str_max = out_buf + size - BUFFER_MARGIN; int8_t initial_depth = nv->depth; int8_t prev_depth = 0; uint8_t need_a_comma = false; *str++ = '{'; // write opening curly while (true) { if (nv->valuetype != TYPE_EMPTY) { if (need_a_comma) { *str++ = ',';} need_a_comma = true; if (js.json_syntax == JSON_SYNTAX_RELAXED) { // write name str += sprintf((char *)str, "%s:", nv->token); } else { str += sprintf((char *)str, "\"%s\":", nv->token); } // check for illegal float values if (nv->valuetype == TYPE_FLOAT) { if (isnan((double)nv->value) || isinf((double)nv->value)) { nv->value = 0;} } // serialize output value (arranged in rough order of likely occurrence) if (nv->valuetype == TYPE_FLOAT) { preprocess_float(nv); str += fntoa(str, nv->value, nv->precision);} else if (nv->valuetype == TYPE_INT) { str += sprintf((char *)str, "%1.0f", (double)nv->value);} else if (nv->valuetype == TYPE_STRING) { str += sprintf((char *)str, "\"%s\"",(char *)*nv->stringp);} else if (nv->valuetype == TYPE_ARRAY) { str += sprintf((char *)str, "[%s]", (char *)*nv->stringp);} else if (nv->valuetype == TYPE_NULL) { str += sprintf((char *)str, "null");} // Note that that "" is NOT null. else if (nv->valuetype == TYPE_DATA) { uint32_t *v = (uint32_t*)&nv->value; str += sprintf(str, "\"0x%lx\"", *v); } else if (nv->valuetype == TYPE_BOOL) { if (fp_FALSE(nv->value)) { str += sprintf(str, "false"); } else { str += sprintf(str, "true"); } } else if (nv->valuetype == TYPE_PARENT) { *str++ = '{'; need_a_comma = false; } } if (str >= str_max) { return (-1);} // signal buffer overrun if ((nv = nv->nx) == NULL) { break;} // end of the list while (nv->depth < prev_depth--) { // iterate the closing curlies need_a_comma = true; *str++ = '}'; } prev_depth = nv->depth; } // closing curlies and NEWLINE while (prev_depth-- > initial_depth) { *str++ = '}';} str += sprintf((char *)str, "}\n"); // using sprintf for this last one ensures a NUL termination if (str > out_buf + size) { return (-1);} return (str - out_buf); #endif }