From 8aa084918f78698969f454058ca36028dc157e97 Mon Sep 17 00:00:00 2001 From: Dave Gamble Date: Tue, 5 Feb 2013 17:27:59 +0000 Subject: [PATCH] Revert last patch. Simpler fix for empty arrays/objects is to handle them explicitly and then bail. Saves plenty of unnecessary state-tracking. git-svn-id: http://svn.code.sf.net/p/cjson/code@45 e3330c51-1366-4df0-8b21-3ccf24e3d50e --- cJSON.c | 48 +++++++++++++++++++++++++++++++----------------- 1 file changed, 31 insertions(+), 17 deletions(-) diff --git a/cJSON.c b/cJSON.c index 027f440..9262cb4 100644 --- a/cJSON.c +++ b/cJSON.c @@ -327,28 +327,32 @@ static const char *parse_array(cJSON *item,const char *value) /* Render an array to text */ static char *print_array(cJSON *item,int depth,int fmt) { - char **entries=0; + char **entries; char *out=0,*ptr,*ret;int len=5; cJSON *child=item->child; int numentries=0,i=0,fail=0; /* How many entries in the array? */ while (child) numentries++,child=child->next; - if (numentries) + /* Explicitly handle numentries==0 */ + if (!numentries) { - /* Allocate an array to hold the values for each */ - entries=(char**)cJSON_malloc(numentries*sizeof(char*)); - if (!entries) return 0; - memset(entries,0,numentries*sizeof(char*)); - /* Retrieve all the results: */ - child=item->child; - while (child && !fail) - { - ret=print_value(child,depth+1,fmt); - entries[i++]=ret; - if (ret) len+=strlen(ret)+2+(fmt?1:0); else fail=1; - child=child->next; - } + out=(char*)cJSON_malloc(3); + if (out) strcpy(out,"[]"); + return out; + } + /* Allocate an array to hold the values for each */ + entries=(char**)cJSON_malloc(numentries*sizeof(char*)); + if (!entries) return 0; + memset(entries,0,numentries*sizeof(char*)); + /* Retrieve all the results: */ + child=item->child; + while (child && !fail) + { + ret=print_value(child,depth+1,fmt); + entries[i++]=ret; + if (ret) len+=strlen(ret)+2+(fmt?1:0); else fail=1; + child=child->next; } /* If we didn't fail, try to malloc the output string */ @@ -360,7 +364,7 @@ static char *print_array(cJSON *item,int depth,int fmt) if (fail) { for (i=0;inext; + /* Explicitly handle empty object case */ + if (!numentries) + { + out=cJSON_malloc(fmt?depth+3:3); + if (!out) return 0; + ptr=out;*ptr++='{'; + if (fmt) {*ptr++='\n';for (i=0;i