2 Copyright (c) 2009 Dave Gamble
4 Permission is hereby granted, free of charge, to any person obtaining a copy
5 of this software and associated documentation files (the "Software"), to deal
6 in the Software without restriction, including without limitation the rights
7 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 copies of the Software, and to permit persons to whom the Software is
9 furnished to do so, subject to the following conditions:
11 The above copyright notice and this permission notice shall be included in
12 all copies or substantial portions of the Software.
14 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24 /* JSON parser in C. */
35 /* Determine the number of bits that an integer has using the preprocessor */
38 #define INTEGER_SIZE 0x0010
39 #elif INT_MAX == 2147483647
41 #define INTEGER_SIZE 0x0100
42 #elif INT_MAX == 9223372036854775807
44 #define INTEGER_SIZE 0x1000
46 #error "Failed to determine the size of an integer"
49 static const char *global_ep = NULL;
51 const char *cJSON_GetErrorPtr(void)
56 /* case insensitive strcmp */
57 static int cJSON_strcasecmp(const char *s1, const char *s2)
61 return (s1 == s2) ? 0 : 1; /* both NULL? */
67 for(; tolower(*(const unsigned char *)s1) == tolower(*(const unsigned char *)s2); ++s1, ++s2)
75 return tolower(*(const unsigned char *)s1) - tolower(*(const unsigned char *)s2);
78 static void *(*cJSON_malloc)(size_t sz) = malloc;
79 static void (*cJSON_free)(void *ptr) = free;
81 static char* cJSON_strdup(const char* str)
86 len = strlen(str) + 1;
87 if (!(copy = (char*)cJSON_malloc(len)))
91 memcpy(copy, str, len);
96 void cJSON_InitHooks(cJSON_Hooks* hooks)
101 cJSON_malloc = malloc;
106 cJSON_malloc = (hooks->malloc_fn) ? hooks->malloc_fn : malloc;
107 cJSON_free = (hooks->free_fn) ? hooks->free_fn : free;
110 /* Internal constructor. */
111 static cJSON *cJSON_New_Item(void)
113 cJSON* node = (cJSON*)cJSON_malloc(sizeof(cJSON));
116 memset(node, '\0', sizeof(cJSON));
122 /* Delete a cJSON structure. */
123 void cJSON_Delete(cJSON *c)
129 if (!(c->type & cJSON_IsReference) && c->child)
131 cJSON_Delete(c->child);
133 if (!(c->type & cJSON_IsReference) && c->valuestring)
135 cJSON_free(c->valuestring);
137 if (!(c->type & cJSON_StringIsConst) && c->string)
139 cJSON_free(c->string);
146 /* Parse the input text to generate a number, and populate the result into item. */
147 static const char *parse_number(cJSON *item, const char *num)
153 int signsubscale = 1;
167 if ((*num >= '1') && (*num <= '9'))
171 n = (n * 10.0) + (*num++ - '0');
173 while ((*num >= '0') && (*num<='9'));
175 /* Fractional part? */
176 if ((*num == '.') && (num[1] >= '0') && (num[1] <= '9'))
181 n = (n *10.0) + (*num++ - '0');
183 } while ((*num >= '0') && (*num <= '9'));
186 if ((*num == 'e') || (*num == 'E'))
194 else if (*num == '-')
200 while ((*num>='0') && (*num<='9'))
202 subscale = (subscale * 10) + (*num++ - '0');
206 /* number = +/- number.fraction * 10^+/- exponent */
207 n = sign * n * pow(10.0, (scale + subscale * signsubscale));
209 item->valuedouble = n;
210 item->valueint = (int)n;
211 item->type = cJSON_Number;
216 /* calculate the next largest power of 2 */
217 static int pow2gt (int x)
224 #if INTEGER_SIZE & 0x1110 /* at least 16 bit */
227 #if INTEGER_SIZE & 0x1100 /* at least 32 bit */
230 #if INT_SIZE & 0x1000 /* 64 bit */
244 /* realloc printbuffer if necessary to have at least "needed" bytes more */
245 static char* ensure(printbuffer *p, int needed)
247 char *newbuffer = NULL;
249 if (!p || !p->buffer)
254 if (needed <= p->length)
256 return p->buffer + p->offset;
259 newsize = pow2gt(needed);
260 newbuffer = (char*)cJSON_malloc(newsize);
263 cJSON_free(p->buffer);
271 memcpy(newbuffer, p->buffer, p->length);
273 cJSON_free(p->buffer);
275 p->buffer = newbuffer;
277 return newbuffer + p->offset;
280 /* calculate the new length of the string in a printbuffer */
281 static int update(const printbuffer *p)
284 if (!p || !p->buffer)
288 str = p->buffer + p->offset;
290 return p->offset + strlen(str);
293 /* Render the number nicely from the given item into a string. */
294 static char *print_number(const cJSON *item, printbuffer *p)
297 double d = item->valuedouble;
298 /* special case for 0. */
307 str = (char*)cJSON_malloc(2);
314 /* value is an int */
315 else if ((fabs(((double)item->valueint) - d) <= DBL_EPSILON) && (d <= INT_MAX) && (d >= INT_MIN))
323 /* 2^64+1 can be represented in 21 chars. */
324 str = (char*)cJSON_malloc(21);
328 sprintf(str, "%d", item->valueint);
331 /* value is a floating point number */
336 /* This is a nice tradeoff. */
341 /* This is a nice tradeoff. */
342 str=(char*)cJSON_malloc(64);
346 /* This checks for NaN and Infinity */
349 sprintf(str, "null");
351 else if ((fabs(floor(d) - d) <= DBL_EPSILON) && (fabs(d) < 1.0e60))
353 sprintf(str, "%.0f", d);
355 else if ((fabs(d) < 1.0e-6) || (fabs(d) > 1.0e9))
357 sprintf(str, "%e", d);
361 sprintf(str, "%f", d);
368 /* parse 4 digit hexadecimal number */
369 static unsigned parse_hex4(const char *str)
373 if ((*str >= '0') && (*str <= '9'))
377 else if ((*str >= 'A') && (*str <= 'F'))
379 h += 10 + (*str) - 'A';
381 else if ((*str >= 'a') && (*str <= 'f'))
383 h += 10 + (*str) - 'a';
394 if ((*str >= '0') && (*str <= '9'))
398 else if ((*str >= 'A') && (*str <= 'F'))
400 h += 10 + (*str) - 'A';
402 else if ((*str >= 'a') && (*str <= 'f'))
404 h += 10 + (*str) - 'a';
414 if ((*str >= '0') && (*str <= '9'))
418 else if ((*str >= 'A') && (*str <= 'F'))
420 h += 10 + (*str) - 'A';
422 else if ((*str >= 'a') && (*str <= 'f'))
424 h += 10 + (*str) - 'a';
434 if ((*str >= '0') && (*str <= '9'))
438 else if ((*str >= 'A') && (*str <= 'F'))
440 h += 10 + (*str) - 'A';
442 else if ((*str >= 'a') && (*str <= 'f'))
444 h += 10 + (*str) - 'a';
454 /* first bytes of UTF8 encoding for a given length in bytes */
455 static const unsigned char firstByteMark[7] =
457 0x00, /* should never happen */
466 /* Parse the input text into an unescaped cstring, and populate item. */
467 static const char *parse_string(cJSON *item, const char *str, const char **ep)
469 const char *ptr = str + 1;
470 const char *end_ptr =str + 1;
484 while ((*end_ptr != '\"') && *end_ptr && ++len)
486 if (*end_ptr++ == '\\')
488 if (*end_ptr == '\0')
490 /* prevent buffer overflow when last input character is a backslash */
493 /* Skip escaped quotes. */
498 /* This is at most how long we need for the string, roughly. */
499 out = (char*)cJSON_malloc(len + 1);
504 item->valuestring = out; /* assign here so out will be deleted during cJSON_Delete() later */
505 item->type = cJSON_String;
509 /* loop through the string literal */
510 while (ptr < end_ptr)
516 /* escape sequence */
543 /* transcode utf16 to utf8. See RFC2781 and RFC3629. */
544 uc = parse_hex4(ptr + 1); /* get the unicode char. */
552 /* check for invalid. */
553 if (((uc >= 0xDC00) && (uc <= 0xDFFF)) || (uc == 0))
559 /* UTF16 surrogate pairs. */
560 if ((uc >= 0xD800) && (uc<=0xDBFF))
562 if ((ptr + 6) > end_ptr)
568 if ((ptr[1] != '\\') || (ptr[2] != 'u'))
570 /* missing second-half of surrogate. */
574 uc2 = parse_hex4(ptr + 3);
575 ptr += 6; /* \uXXXX */
576 if ((uc2 < 0xDC00) || (uc2 > 0xDFFF))
578 /* invalid second-half of surrogate. */
582 /* calculate unicode codepoint from the surrogate pair */
583 uc = 0x10000 + (((uc & 0x3FF) << 10) | (uc2 & 0x3FF));
587 * takes at maximum 4 bytes to encode:
588 * 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */
592 /* normal ascii, encoding 0xxxxxxx */
597 /* two bytes, encoding 110xxxxx 10xxxxxx */
600 else if (uc < 0x10000)
602 /* three bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx */
610 *--ptr2 = ((uc | 0x80) & 0xBF);
614 *--ptr2 = ((uc | 0x80) & 0xBF);
618 *--ptr2 = ((uc | 0x80) & 0xBF);
621 /* depending on the length in bytes this determines the
622 * encoding ofthe first UTF8 byte */
623 *--ptr2 = (uc | firstByteMark[len]);
643 /* Render the cstring provided to an escaped version that can be printed. */
644 static char *print_string_ptr(const char *str, printbuffer *p)
646 const char *ptr = NULL;
651 unsigned char token = '\0';
662 out = (char*)cJSON_malloc(3);
673 /* set "flag" to 1 if something needs to be escaped */
674 for (ptr = str; *ptr; ptr++)
676 flag |= (((*ptr > 0) && (*ptr < 32)) /* unprintable characters */
677 || (*ptr == '\"') /* double quote */
678 || (*ptr == '\\')) /* backslash */
682 /* no characters have to be escaped */
688 out = ensure(p, len + 3);
692 out = (char*)cJSON_malloc(len + 3);
703 ptr2[len + 1] = '\0';
709 /* calculate additional space that is needed for escaping */
710 while ((token = *ptr) && ++len)
712 if (strchr("\"\\\b\f\n\r\t", token))
714 len++; /* +1 for the backslash */
718 len += 5; /* +5 for \uXXXX */
725 out = ensure(p, len + 3);
729 out = (char*)cJSON_malloc(len + 3);
739 /* copy the string */
742 if (((unsigned char)*ptr > 31) && (*ptr != '\"') && (*ptr != '\\'))
744 /* normal character, copy */
749 /* character needs to be escaped */
751 switch (token = *ptr++)
775 /* escape and print as unicode codepoint */
776 sprintf(ptr2, "u%04x", token);
788 /* Invoke print_string_ptr (which is useful) on an item. */
789 static char *print_string(const cJSON *item, printbuffer *p)
791 return print_string_ptr(item->valuestring, p);
794 /* Predeclare these prototypes. */
795 static const char *parse_value(cJSON *item, const char *value, const char **ep);
796 static char *print_value(const cJSON *item, int depth, int fmt, printbuffer *p);
797 static const char *parse_array(cJSON *item, const char *value, const char **ep);
798 static char *print_array(const cJSON *item, int depth, int fmt, printbuffer *p);
799 static const char *parse_object(cJSON *item, const char *value, const char **ep);
800 static char *print_object(const cJSON *item, int depth, int fmt, printbuffer *p);
802 /* Utility to jump whitespace and cr/lf */
803 static const char *skip(const char *in)
805 while (in && *in && ((unsigned char)*in<=32))
813 /* Parse an object - create a new root, and populate. */
814 cJSON *cJSON_ParseWithOpts(const char *value, const char **return_parse_end, int require_null_terminated)
816 const char *end = NULL;
817 /* use global error pointer if no specific one was given */
818 const char **ep = return_parse_end ? return_parse_end : &global_ep;
819 cJSON *c = cJSON_New_Item();
821 if (!c) /* memory fail */
826 end = parse_value(c, skip(value), ep);
829 /* parse failure. ep is set. */
834 /* if we require null-terminated JSON without appended garbage, skip and then check for a null terminator */
835 if (require_null_terminated)
845 if (return_parse_end)
847 *return_parse_end = end;
853 /* Default options for cJSON_Parse */
854 cJSON *cJSON_Parse(const char *value)
856 return cJSON_ParseWithOpts(value, 0, 0);
859 /* Render a cJSON item/entity/structure to text. */
860 char *cJSON_Print(const cJSON *item)
862 return print_value(item, 0, 1, 0);
865 char *cJSON_PrintUnformatted(const cJSON *item)
867 return print_value(item, 0, 0, 0);
870 char *cJSON_PrintBuffered(const cJSON *item, int prebuffer, int fmt)
873 p.buffer = (char*)cJSON_malloc(prebuffer);
878 p.length = prebuffer;
881 return print_value(item, 0, fmt, &p);
885 /* Parser core - when encountering text, process appropriately. */
886 static const char *parse_value(cJSON *item, const char *value, const char **ep)
894 /* parse the different types of values */
895 if (!strncmp(value, "null", 4))
897 item->type = cJSON_NULL;
900 if (!strncmp(value, "false", 5))
902 item->type = cJSON_False;
905 if (!strncmp(value, "true", 4))
907 item->type = cJSON_True;
913 return parse_string(item, value, ep);
915 if ((*value == '-') || ((*value >= '0') && (*value <= '9')))
917 return parse_number(item, value);
921 return parse_array(item, value, ep);
925 return parse_object(item, value, ep);
933 /* Render a value to text. */
934 static char *print_value(const cJSON *item, int depth, int fmt, printbuffer *p)
944 switch ((item->type) & 0xFF)
957 strcpy(out, "false");
968 out = print_number(item, p);
971 out = print_string(item, p);
974 out = print_array(item, depth, fmt, p);
977 out = print_object(item, depth, fmt, p);
983 switch ((item->type) & 0xFF)
986 out = cJSON_strdup("null");
989 out = cJSON_strdup("false");
992 out = cJSON_strdup("true");
995 out = print_number(item, 0);
998 out = print_string(item, 0);
1001 out = print_array(item, depth, fmt, 0);
1004 out = print_object(item, depth, fmt, 0);
1012 /* Build an array from input text. */
1013 static const char *parse_array(cJSON *item,const char *value,const char **ep)
1015 cJSON *child = NULL;
1023 item->type = cJSON_Array;
1024 value = skip(value + 1);
1031 item->child = child = cJSON_New_Item();
1037 /* skip any spacing, get the value. */
1038 value = skip(parse_value(child, skip(value), ep));
1044 /* loop through the comma separated array elements */
1045 while (*value == ',')
1047 cJSON *new_item = NULL;
1048 if (!(new_item = cJSON_New_Item()))
1053 /* add new item to end of the linked list */
1054 child->next = new_item;
1055 new_item->prev = child;
1058 /* go to the next comma */
1059 value = skip(parse_value(child, skip(value + 1), ep));
1079 /* Render an array to text */
1080 static char *print_array(const cJSON *item, int depth, int fmt, printbuffer *p)
1087 cJSON *child = item->child;
1093 /* How many entries in the array? */
1097 child = child->next;
1100 /* Explicitly handle numentries == 0 */
1109 out = (char*)cJSON_malloc(3);
1121 /* Compose the output array. */
1122 /* opening square bracket */
1132 child = item->child;
1133 while (child && !fail)
1135 print_value(child, depth + 1, fmt, p);
1136 p->offset = update(p);
1140 ptr = ensure(p, len + 1);
1153 child = child->next;
1162 out = (p->buffer) + i;
1166 /* Allocate an array to hold the pointers to all printed values */
1167 entries = (char**)cJSON_malloc(numentries * sizeof(char*));
1172 memset(entries, '\0', numentries * sizeof(char*));
1174 /* Retrieve all the results: */
1175 child = item->child;
1176 while (child && !fail)
1178 ret = print_value(child, depth + 1, fmt, 0);
1182 len += strlen(ret) + 2 + (fmt ? 1 : 0);
1188 child = child->next;
1191 /* If we didn't fail, try to malloc the output string */
1194 out = (char*)cJSON_malloc(len);
1196 /* If that fails, we fail. */
1202 /* Handle failure. */
1205 /* free all the entries in the array */
1206 for (i = 0; i < numentries; i++)
1210 cJSON_free(entries[i]);
1213 cJSON_free(entries);
1217 /* Compose the output array. */
1221 for (i = 0; i < numentries; i++)
1223 tmplen = strlen(entries[i]);
1224 memcpy(ptr, entries[i], tmplen);
1226 if (i != (numentries - 1))
1235 cJSON_free(entries[i]);
1237 cJSON_free(entries);
1245 /* Build an object from the text. */
1246 static const char *parse_object(cJSON *item, const char *value, const char **ep)
1248 cJSON *child = NULL;
1251 /* not an object! */
1256 item->type = cJSON_Object;
1257 value = skip(value + 1);
1264 child = cJSON_New_Item();
1265 item->child = child;
1270 /* parse first key */
1271 value = skip(parse_string(child, skip(value), ep));
1276 /* use string as key, not value */
1277 child->string = child->valuestring;
1278 child->valuestring = NULL;
1282 /* invalid object. */
1286 /* skip any spacing, get the value. */
1287 value = skip(parse_value(child, skip(value + 1), ep));
1293 while (*value == ',')
1295 cJSON *new_item = NULL;
1296 if (!(new_item = cJSON_New_Item()))
1301 /* add to linked list */
1302 child->next = new_item;
1303 new_item->prev = child;
1306 value = skip(parse_string(child, skip(value + 1), ep));
1312 /* use string as key, not value */
1313 child->string = child->valuestring;
1314 child->valuestring = NULL;
1318 /* invalid object. */
1322 /* skip any spacing, get the value. */
1323 value = skip(parse_value(child, skip(value + 1), ep));
1340 /* Render an object to text. */
1341 static char *print_object(const cJSON *item, int depth, int fmt, printbuffer *p)
1343 char **entries = NULL;
1344 char **names = NULL;
1352 cJSON *child = item->child;
1357 /* Count the number of entries. */
1361 child = child->next;
1364 /* Explicitly handle empty object case */
1369 out = ensure(p, fmt ? depth + 4 : 3);
1373 out = (char*)cJSON_malloc(fmt ? depth + 4 : 3);
1383 for (i = 0; i < depth; i++)
1396 /* Compose the output: */
1398 len = fmt ? 2 : 1; /* fmt: {\n */
1399 ptr = ensure(p, len + 1);
1413 child = item->child;
1419 ptr = ensure(p, depth);
1424 for (j = 0; j < depth; j++)
1432 print_string_ptr(child->string, p);
1433 p->offset = update(p);
1436 ptr = ensure(p, len);
1449 print_value(child, depth, fmt, p);
1450 p->offset = update(p);
1452 /* print comma if not last */
1453 len = (fmt ? 1 : 0) + (child->next ? 1 : 0);
1454 ptr = ensure(p, len + 1);
1471 child = child->next;
1474 ptr = ensure(p, fmt ? (depth + 1) : 2);
1481 for (i = 0; i < (depth - 1); i++)
1488 out = (p->buffer) + i;
1492 /* Allocate space for the names and the objects */
1493 entries = (char**)cJSON_malloc(numentries * sizeof(char*));
1498 names = (char**)cJSON_malloc(numentries * sizeof(char*));
1501 cJSON_free(entries);
1504 memset(entries, '\0', sizeof(char*) * numentries);
1505 memset(names, '\0', sizeof(char*) * numentries);
1507 /* Collect all the results into our arrays: */
1508 child = item->child;
1514 while (child && !fail)
1516 names[i] = str = print_string_ptr(child->string, 0); /* print key */
1517 entries[i++] = ret = print_value(child, depth, fmt, 0);
1520 len += strlen(ret) + strlen(str) + 2 + (fmt ? 2 + depth : 0);
1526 child = child->next;
1529 /* Try to allocate the output string */
1532 out = (char*)cJSON_malloc(len);
1539 /* Handle failure */
1542 /* free all the printed keys and values */
1543 for (i = 0; i < numentries; i++)
1547 cJSON_free(names[i]);
1551 cJSON_free(entries[i]);
1555 cJSON_free(entries);
1559 /* Compose the output: */
1567 for (i = 0; i < numentries; i++)
1571 for (j = 0; j < depth; j++)
1576 tmplen = strlen(names[i]);
1577 memcpy(ptr, names[i], tmplen);
1584 strcpy(ptr, entries[i]);
1585 ptr += strlen(entries[i]);
1586 if (i != (numentries - 1))
1595 cJSON_free(names[i]);
1596 cJSON_free(entries[i]);
1600 cJSON_free(entries);
1603 for (i = 0; i < (depth - 1); i++)
1615 /* Get Array size/item / object item. */
1616 int cJSON_GetArraySize(const cJSON *array)
1618 cJSON *c = array->child;
1628 cJSON *cJSON_GetArrayItem(const cJSON *array, int item)
1630 cJSON *c = array ? array->child : NULL;
1631 while (c && item > 0)
1640 cJSON *cJSON_GetObjectItem(const cJSON *object, const char *string)
1642 cJSON *c = object ? object->child : NULL;
1643 while (c && cJSON_strcasecmp(c->string, string))
1650 int cJSON_HasObjectItem(const cJSON *object,const char *string)
1652 return cJSON_GetObjectItem(object, string) ? 1 : 0;
1655 /* Utility for array list handling. */
1656 static void suffix_object(cJSON *prev, cJSON *item)
1662 /* Utility for handling references. */
1663 static cJSON *create_reference(const cJSON *item)
1665 cJSON *ref = cJSON_New_Item();
1670 memcpy(ref, item, sizeof(cJSON));
1672 ref->type |= cJSON_IsReference;
1673 ref->next = ref->prev = NULL;
1677 /* Add item to array/object. */
1678 void cJSON_AddItemToArray(cJSON *array, cJSON *item)
1680 cJSON *c = array->child;
1687 /* list is empty, start new one */
1688 array->child = item;
1692 /* append to the end */
1697 suffix_object(c, item);
1701 void cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item)
1708 /* free old key and set new one */
1711 cJSON_free(item->string);
1713 item->string = cJSON_strdup(string);
1715 cJSON_AddItemToArray(object,item);
1718 /* Add an item to an object with constant string as key */
1719 void cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item)
1725 if (!(item->type & cJSON_StringIsConst) && item->string)
1727 cJSON_free(item->string);
1729 item->string = (char*)string;
1730 item->type |= cJSON_StringIsConst;
1731 cJSON_AddItemToArray(object, item);
1734 void cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item)
1736 cJSON_AddItemToArray(array, create_reference(item));
1739 void cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item)
1741 cJSON_AddItemToObject(object, string, create_reference(item));
1744 cJSON *cJSON_DetachItemFromArray(cJSON *array, int which)
1746 cJSON *c = array->child;
1747 while (c && (which > 0))
1754 /* item doesn't exist */
1759 /* not the first element */
1760 c->prev->next = c->next;
1764 c->next->prev = c->prev;
1766 if (c==array->child)
1768 array->child = c->next;
1770 /* make sure the detached item doesn't point anywhere anymore */
1771 c->prev = c->next = NULL;
1776 void cJSON_DeleteItemFromArray(cJSON *array, int which)
1778 cJSON_Delete(cJSON_DetachItemFromArray(array, which));
1781 cJSON *cJSON_DetachItemFromObject(cJSON *object, const char *string)
1784 cJSON *c = object->child;
1785 while (c && cJSON_strcasecmp(c->string,string))
1792 return cJSON_DetachItemFromArray(object, i);
1798 void cJSON_DeleteItemFromObject(cJSON *object, const char *string)
1800 cJSON_Delete(cJSON_DetachItemFromObject(object, string));
1803 /* Replace array/object items with new ones. */
1804 void cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem)
1806 cJSON *c = array->child;
1807 while (c && (which > 0))
1814 cJSON_AddItemToArray(array, newitem);
1818 newitem->prev = c->prev;
1820 if (c == array->child)
1822 array->child = newitem;
1826 newitem->prev->next = newitem;
1830 void cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem)
1832 cJSON *c = array->child;
1833 while (c && (which > 0))
1842 newitem->next = c->next;
1843 newitem->prev = c->prev;
1846 newitem->next->prev = newitem;
1848 if (c == array->child)
1850 array->child = newitem;
1854 newitem->prev->next = newitem;
1856 c->next = c->prev = NULL;
1860 void cJSON_ReplaceItemInObject(cJSON *object, const char *string, cJSON *newitem)
1863 cJSON *c = object->child;
1864 while(c && cJSON_strcasecmp(c->string, string))
1871 /* free the old string if not const */
1872 if (!(newitem->type & cJSON_StringIsConst) && newitem->string)
1874 cJSON_free(newitem->string);
1877 newitem->string = cJSON_strdup(string);
1878 cJSON_ReplaceItemInArray(object, i, newitem);
1882 /* Create basic types: */
1883 cJSON *cJSON_CreateNull(void)
1885 cJSON *item = cJSON_New_Item();
1888 item->type = cJSON_NULL;
1894 cJSON *cJSON_CreateTrue(void)
1896 cJSON *item = cJSON_New_Item();
1899 item->type = cJSON_True;
1905 cJSON *cJSON_CreateFalse(void)
1907 cJSON *item = cJSON_New_Item();
1910 item->type = cJSON_False;
1916 cJSON *cJSON_CreateBool(int b)
1918 cJSON *item = cJSON_New_Item();
1921 item->type = b ? cJSON_True : cJSON_False;
1927 cJSON *cJSON_CreateNumber(double num)
1929 cJSON *item = cJSON_New_Item();
1932 item->type = cJSON_Number;
1933 item->valuedouble = num;
1934 item->valueint = (int)num;
1940 cJSON *cJSON_CreateString(const char *string)
1942 cJSON *item = cJSON_New_Item();
1945 item->type = cJSON_String;
1946 item->valuestring = cJSON_strdup(string);
1947 if(!item->valuestring)
1957 cJSON *cJSON_CreateArray(void)
1959 cJSON *item = cJSON_New_Item();
1962 item->type=cJSON_Array;
1968 cJSON *cJSON_CreateObject(void)
1970 cJSON *item = cJSON_New_Item();
1973 item->type = cJSON_Object;
1979 /* Create Arrays: */
1980 cJSON *cJSON_CreateIntArray(const int *numbers, int count)
1985 cJSON *a = cJSON_CreateArray();
1986 for(i = 0; a && (i < count); i++)
1988 n = cJSON_CreateNumber(numbers[i]);
2000 suffix_object(p, n);
2008 cJSON *cJSON_CreateFloatArray(const float *numbers, int count)
2013 cJSON *a = cJSON_CreateArray();
2014 for(i = 0; a && (i < count); i++)
2016 n = cJSON_CreateNumber(numbers[i]);
2028 suffix_object(p, n);
2036 cJSON *cJSON_CreateDoubleArray(const double *numbers, int count)
2041 cJSON *a = cJSON_CreateArray();
2042 for(i = 0;a && (i < count); i++)
2044 n = cJSON_CreateNumber(numbers[i]);
2056 suffix_object(p, n);
2064 cJSON *cJSON_CreateStringArray(const char **strings, int count)
2069 cJSON *a = cJSON_CreateArray();
2070 for (i = 0; a && (i < count); i++)
2072 n = cJSON_CreateString(strings[i]);
2093 cJSON *cJSON_Duplicate(const cJSON *item, int recurse)
2095 cJSON *newitem = NULL;
2098 cJSON *newchild = NULL;
2100 /* Bail on bad ptr */
2105 /* Create new item */
2106 newitem = cJSON_New_Item();
2111 /* Copy over all vars */
2112 newitem->type = item->type & (~cJSON_IsReference);
2113 newitem->valueint = item->valueint;
2114 newitem->valuedouble = item->valuedouble;
2115 if (item->valuestring)
2117 newitem->valuestring = cJSON_strdup(item->valuestring);
2118 if (!newitem->valuestring)
2120 cJSON_Delete(newitem);
2126 newitem->string = cJSON_strdup(item->string);
2127 if (!newitem->string)
2129 cJSON_Delete(newitem);
2133 /* If non-recursive, then we're done! */
2138 /* Walk the ->next chain for the child. */
2142 newchild = cJSON_Duplicate(cptr, 1); /* Duplicate (with recurse) each item in the ->next chain */
2145 cJSON_Delete(newitem);
2150 /* If newitem->child already set, then crosswire ->prev and ->next and move on */
2151 nptr->next = newchild;
2152 newchild->prev = nptr;
2157 /* Set newitem->child and move to it */
2158 newitem->child = newchild; nptr = newchild;
2166 void cJSON_Minify(char *json)
2175 else if (*json == '\t')
2177 /* Whitespace characters. */
2180 else if (*json == '\r')
2184 else if (*json=='\n')
2188 else if ((*json == '/') && (json[1] == '/'))
2190 /* double-slash comments, to end of line. */
2191 while (*json && (*json != '\n'))
2196 else if ((*json == '/') && (json[1] == '*'))
2198 /* multiline comments. */
2199 while (*json && !((*json == '*') && (json[1] == '/')))
2205 else if (*json == '\"')
2207 /* string literals, which are \" sensitive. */
2209 while (*json && (*json != '\"'))
2221 /* All other characters. */
2226 /* and null-terminate. */