cJSON icon indicating copy to clipboard operation
cJSON copied to clipboard

question about cJSON_Number

Open helo-ch opened this issue 8 years ago • 2 comments

I have a question about cJSON_Number : in the cJSON struct there are 2 numbers, valueint and valuedouble. From what I saw while doing some tests, I understand that if type == cJSON_Number, I understood the number is stored in both values. What I would like to know if is there is any way to know if a cJSON_Number is an int or a double.

I am asking this because I needed a function to convert cJSON objects to strings so I created one :

void cJSON_ToString(cJSON* json, char str[200])
{
  cJSON* p_courant = json->child;
  int j = cJSON_GetArraySize(json);
  int i;
  char n[12];
  strcat(str,"{");
  for (i = 1; i <= j ; i++)
  {
    strcat(str,"\"");
    strcat(str,(char*)(p_courant->string));
    strcat(str,"\" : ");
    if (p_courant->type == cJSON_String)
    {
      strcat(str,"\"");
      strcat(str,(char*)(p_courant->valuestring));
      strcat(str,"\"");
    }
    else if (p_courant->type == cJSON_Number)
    {
      sprintf(n,"%f",(double)(p_courant->valuedouble));
      strcat(str,n);
    }
    if (i != j)
    {
      strcat(str,",");
      p_courant = p_courant->next;
    }
  }
  strcat(str,"}");
}

but I would like to be able to deal with both integers and floats, which I don't know how to do right now because cJSON_Number can be either.

helo-ch avatar Dec 13 '17 10:12 helo-ch

Why don't you use cJSON_Print, or in your case cJSON_PrintPreallocated because you print to a fixed size buffer? It should print numbers correctly without decimal point if it is an integer.

cJSON_bool cJSON_ToString(cJSON * const json, char buffer[200]) {
    return cJSON_PrintPreallocated(json, buffer, 200, 0);
}

valueint is only there for compatibility reasons, cJSON internally only uses valuedouble (but sets valueint as well for old applications).

If you want to find out if a number is an integer, there are several ways to do it.

  1. ((double)valueint) == valuedouble
  2. ((double)((int)valuedouble)) == valuedouble (not sure if there can be any rounding errors
  3. double fractional; (modf(valuedouble, &fractional) == 0)

FSMaxB avatar Dec 13 '17 12:12 FSMaxB

using cJSON_Print or cJSON_PrintPreallocated didn't work with what I want to do, but your tips to find out if a number is an integer are working perfectly, thanks!

helo-ch avatar Dec 14 '17 07:12 helo-ch