0

I am using cJSON but somehow I can't get the strings to work:

void myfile()
{
  cJSON* type = NULL;
  char text1[]="{\n\"name\": \"Jack (\\\"Bee\\\") Nimble\", \n\"format\": {\"type\":       \"rect\", \n\"width\":      1920, \n\"height\":     1080, \n\"interlace\":  false,\"frame rate\": 24\n}\n}";
  cJSON * root = cJSON_Parse(text);
  cJSON * format = cJSON_GetObjectItem(root,"format"); 
  int framerate = cJSON_GetObjectItem(format,"frame rate")->valueint;
  type = cJSON_GetObjectItem(format,"type")->valuestring;
  char * rendered = cJSON_Print(root);
  cJSON_Delete(root);
  printf("rate = %d, type = %s \n", framerate, type) ;
}

I only get garbage. I also tried this but it didn't even compile:

char *type[] = cJSON_GetObjectItem(format,"type")->valuestring;

Sled
  • 18,541
  • 27
  • 119
  • 168
Tom
  • 2,545
  • 5
  • 31
  • 71
  • `cJSON* type = NULL;`, `type = %s` - are you sure you should be printing it this way? If `cJSON` isn't typedefed to a `char` you get UB. – user4520 Dec 04 '15 at 21:46
  • I want a char at the end so i can print it with `%s` what do I have to do for that ? – Tom Dec 04 '15 at 21:49
  • try `char *type = cJSON_GetObjectItem(format,"type")->valuestring;` and `printf("rate = %d, type = %s \n", framerate, type) ;` move to before `cJSON_Delete(root);` – BLUEPIXY Dec 04 '15 at 22:21

1 Answers1

2
char text[]="{\n\"name\": \"Jack (\\\"Bee\\\") Nimble\", \n\"format\": {\"type\":       \"rect\", \n\"width\":      1920, \n\"height\":     1080, \n\"interlace\":  false,\"frame rate\": 24\n}\n}";
cJSON * root   = cJSON_Parse(text);
cJSON * format = cJSON_GetObjectItem(root,"format"); 
cJSON * type   = cJSON_GetObjectItem(format,"type");
int framerate = cJSON_GetObjectItem(format,"frame rate")->valueint;
char * rendered = cJSON_Print(root);
printf("%s\n", rendered);
printf("rate = %d, type = %s \n", framerate, type->valuestring);
free(rendered);
cJSON_Delete(root);
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70