Correct comment and variable declaration style to be more compatible. Added cJSONUtils_SortObject for sorting the members of an object alphabetically.

git-svn-id: svn://svn.code.sf.net/p/cjson/code@70 e3330c51-1366-4df0-8b21-3ccf24e3d50e
This commit is contained in:
Dave Gamble 2015-02-13 19:19:26 +00:00
parent 1d9b70e706
commit c4ddd7aaa3
3 changed files with 136 additions and 66 deletions

View File

@ -4,7 +4,7 @@
#include <stdio.h>
#include "cJSON_Utils.h"
// JSON Pointer implementation:
/* JSON Pointer implementation: */
static int cJSONUtils_Pstrcasecmp(const char *a,const char *e)
{
if (!a || !e) return (a==e)?0:1;
@ -31,10 +31,11 @@ static void cJSONUtils_PointerEncodedstrcpy(char *d,const char *s)
char *cJSONUtils_FindPointerFromObjectTo(cJSON *object,cJSON *target)
{
int type=object->type,c=0;cJSON *obj=0;
if (object==target) return strdup("");
int type=object->type,c=0;
for (cJSON *obj=object->child;obj;obj=obj->next,c++)
for (obj=object->child;obj;obj=obj->next,c++)
{
char *found=cJSONUtils_FindPointerFromObjectTo(obj,target);
if (found)
@ -73,7 +74,7 @@ cJSON *cJSONUtils_GetPointer(cJSON *object,const char *pointer)
}
else if (object->type==cJSON_Object)
{
object=object->child; while (object && cJSONUtils_Pstrcasecmp(object->string,pointer)) object=object->next; // GetObjectItem.
object=object->child; while (object && cJSONUtils_Pstrcasecmp(object->string,pointer)) object=object->next; /* GetObjectItem. */
while (*pointer && *pointer!='/') pointer++;
}
else return 0;
@ -81,7 +82,7 @@ cJSON *cJSONUtils_GetPointer(cJSON *object,const char *pointer)
return object;
}
// JSON Patch implementation.
/* JSON Patch implementation. */
static void cJSONUtils_InplaceDecodePointerString(char *string)
{
char *s2=string;
@ -91,14 +92,13 @@ static void cJSONUtils_InplaceDecodePointerString(char *string)
static cJSON *cJSONUtils_PatchDetach(cJSON *object,const char *path)
{
char *parentptr=0,*childptr=0;cJSON *parent=0;
char *parentptr=0,*childptr=0;cJSON *parent=0,*ret=0;
parentptr=strdup(path); childptr=strrchr(parentptr,'/'); if (childptr) *childptr++=0;
parent=cJSONUtils_GetPointer(object,parentptr);
cJSONUtils_InplaceDecodePointerString(childptr);
cJSON *ret=0;
if (!parent) ret=0; // Couldn't find object to remove child from.
if (!parent) ret=0; /* Couldn't find object to remove child from. */
else if (parent->type==cJSON_Array) ret=cJSON_DetachItemFromArray(parent,atoi(childptr));
else if (parent->type==cJSON_Object) ret=cJSON_DetachItemFromObject(parent,childptr);
free(parentptr);
@ -107,18 +107,18 @@ static cJSON *cJSONUtils_PatchDetach(cJSON *object,const char *path)
static int cJSONUtils_Compare(cJSON *a,cJSON *b)
{
if (a->type!=b->type) return -1; // mismatched type.
if (a->type!=b->type) return -1; /* mismatched type. */
switch (a->type)
{
case cJSON_Number: return (a->valueint!=b->valueint || a->valuedouble!=b->valuedouble)?-2:0; // numeric mismatch.
case cJSON_String: return (strcmp(a->valuestring,b->valuestring)!=0)?-3:0; // string mismatch.
case cJSON_Number: return (a->valueint!=b->valueint || a->valuedouble!=b->valuedouble)?-2:0; /* numeric mismatch. */
case cJSON_String: return (strcmp(a->valuestring,b->valuestring)!=0)?-3:0; /* string mismatch. */
case cJSON_Array: for (a=a->child,b=b->child;a && b;a=a->next,b=b->next) {int err=cJSONUtils_Compare(a,b);if (err) return err;}
return (a || b)?-4:0; // array size mismatch.
return (a || b)?-4:0; /* array size mismatch. */
case cJSON_Object:
if (cJSON_GetArraySize(a)!=cJSON_GetArraySize(b)) return -5; // object length mismatch.
if (cJSON_GetArraySize(a)!=cJSON_GetArraySize(b)) return -5; /* object length mismatch. */
for (a=a->child;a;a=a->next)
{
int err=0;cJSON *s=cJSON_GetObjectItem(b,a->string); if (!s) return -6; // missing object member.
int err=0;cJSON *s=cJSON_GetObjectItem(b,a->string); if (!s) return -6; /* missing object member. */
err=cJSONUtils_Compare(a,s);if (err) return err;
}
return 0;
@ -129,11 +129,11 @@ static int cJSONUtils_Compare(cJSON *a,cJSON *b)
static int cJSONUtils_ApplyPatch(cJSON *object,cJSON *patch)
{
cJSON *op=0,*path=0,*value=0;int opcode=0;
cJSON *op=0,*path=0,*value=0,*parent=0;int opcode=0;char *parentptr=0,*childptr=0;
op=cJSON_GetObjectItem(patch,"op");
path=cJSON_GetObjectItem(patch,"path");
if (!op || !path) return 2; // malformed patch.
if (!op || !path) return 2; /* malformed patch. */
if (!strcmp(op->valuestring,"add")) opcode=0;
else if (!strcmp(op->valuestring,"remove")) opcode=1;
@ -141,41 +141,40 @@ static int cJSONUtils_ApplyPatch(cJSON *object,cJSON *patch)
else if (!strcmp(op->valuestring,"move")) opcode=3;
else if (!strcmp(op->valuestring,"copy")) opcode=4;
else if (!strcmp(op->valuestring,"test")) return cJSONUtils_Compare(cJSONUtils_GetPointer(object,path->valuestring),cJSON_GetObjectItem(patch,"value"));
else return 3; // unknown opcode.
else return 3; /* unknown opcode. */
if (opcode==1 || opcode==2) // Remove/Replace
if (opcode==1 || opcode==2) /* Remove/Replace */
{
cJSON_Delete(cJSONUtils_PatchDetach(object,path->valuestring)); // Get rid of old.
if (opcode==1) return 0; // For Remove, this is job done.
cJSON_Delete(cJSONUtils_PatchDetach(object,path->valuestring)); /* Get rid of old. */
if (opcode==1) return 0; /* For Remove, this is job done. */
}
if (opcode==3 || opcode==4) // Copy/Move uses "from".
if (opcode==3 || opcode==4) /* Copy/Move uses "from". */
{
cJSON *from=cJSON_GetObjectItem(patch,"from"); if (!from) return 4; // missing "from" for copy/move.
cJSON *from=cJSON_GetObjectItem(patch,"from"); if (!from) return 4; /* missing "from" for copy/move. */
if (opcode==3) value=cJSONUtils_PatchDetach(object,from->valuestring);
if (opcode==4) value=cJSONUtils_GetPointer(object,from->valuestring);
if (!value) return 5; // missing "from" for copy/move.
if (!value) return 5; /* missing "from" for copy/move. */
if (opcode==4) value=cJSON_Duplicate(value,1);
if (!value) return 6; // out of memory for copy/move.
if (!value) return 6; /* out of memory for copy/move. */
}
else // Add/Replace uses "value".
else /* Add/Replace uses "value". */
{
value=cJSON_GetObjectItem(patch,"value");
if (!value) return 7; // missing "value" for add/replace.
if (!value) return 7; /* missing "value" for add/replace. */
value=cJSON_Duplicate(value,1);
if (!value) return 8; // out of memory for add/replace.
if (!value) return 8; /* out of memory for add/replace. */
}
// Now, just add "value" to "path".
char *parentptr=0,*childptr=0;cJSON *parent=0;
/* Now, just add "value" to "path". */
parentptr=strdup(path->valuestring); childptr=strrchr(parentptr,'/'); if (childptr) *childptr++=0;
parent=cJSONUtils_GetPointer(object,parentptr);
cJSONUtils_InplaceDecodePointerString(childptr);
// add, remove, replace, move, copy, test.
if (!parent) {free(parentptr); return 9;} // Couldn't find object to add to.
/* add, remove, replace, move, copy, test. */
if (!parent) {free(parentptr); return 9;} /* Couldn't find object to add to. */
else if (parent->type==cJSON_Array)
{
if (!strcmp(childptr,"-")) cJSON_AddItemToArray(parent,value);
@ -194,7 +193,7 @@ static int cJSONUtils_ApplyPatch(cJSON *object,cJSON *patch)
int cJSONUtils_ApplyPatches(cJSON *object,cJSON *patches)
{
int err;
if (!patches->type==cJSON_Array) return 1; // malformed patches.
if (!patches->type==cJSON_Array) return 1; /* malformed patches. */
if (patches) patches=patches->child;
while (patches)
{
@ -240,7 +239,7 @@ static void cJSONUtils_CompareToPatch(cJSON *patches,const char *path,cJSON *fro
case cJSON_Array:
{
int c;char *newpath=(char*)malloc(strlen(path)+23); // Allow space for 64bit int.
int c;char *newpath=(char*)malloc(strlen(path)+23); /* Allow space for 64bit int. */
for (c=0,from=from->child,to=to->child;from && to;from=from->next,to=to->next,c++){
sprintf(newpath,"%s/%d",path,c); cJSONUtils_CompareToPatch(patches,newpath,from,to);
}
@ -251,11 +250,13 @@ static void cJSONUtils_CompareToPatch(cJSON *patches,const char *path,cJSON *fro
}
case cJSON_Object:
for (cJSON *a=from->child;a;a=a->next)
{
cJSON *a;
for (a=from->child;a;a=a->next)
{
if (!cJSON_GetObjectItem(to,a->string)) cJSONUtils_GeneratePatch(patches,"remove",path,a->string,0);
}
for (cJSON *a=to->child;a;a=a->next)
for (a=to->child;a;a=a->next)
{
cJSON *other=cJSON_GetObjectItem(from,a->string);
if (!other) cJSONUtils_GeneratePatch(patches,"add",path,a->string,a);
@ -268,6 +269,7 @@ static void cJSONUtils_CompareToPatch(cJSON *patches,const char *path,cJSON *fro
}
}
return;
}
default: break;
}
@ -281,5 +283,47 @@ cJSON* cJSONUtils_GeneratePatches(cJSON *from,cJSON *to)
return patches;
}
static int cJSONUtils_strcasecmp(const char *s1,const char *s2)
{
if (!s1) return (s1==s2)?0:1;if (!s2) return 1;
for(; tolower(*s1) == tolower(*s2); ++s1, ++s2) if(*s1 == 0) return 0;
return tolower(*(const unsigned char *)s1) - tolower(*(const unsigned char *)s2);
}
static cJSON *cJSONUtils_SortList(cJSON *list)
{
cJSON *first=list,*second=list,*ptr=list;
if (!list || !list->next) return list; /* One entry is sorted already. */
while (ptr) {second=second->next;ptr=ptr->next;if (ptr) ptr=ptr->next;} /* Walk two pointers to find the middle. */
if (second && second->prev) second->prev->next=0; /* Split the lists */
first=cJSONUtils_SortList(first); /* Recursively sort the sub-lists. */
second=cJSONUtils_SortList(second);
list=ptr=0;
while (first && second) /* Merge the sub-lists */
{
if (cJSONUtils_strcasecmp(first->string,second->string)<0)
{
if (!list) list=ptr=first;
else {ptr->next=first;first->prev=ptr;ptr=first;}
first=first->next;
}
else
{
if (!list) list=ptr=second;
else {ptr->next=second;second->prev=ptr;ptr=second;}
second=second->next;
}
}
if (first) { if (!list) return first; ptr->next=first; first->prev=ptr; } /* Append any tails. */
if (second) { if (!list) return second; ptr->next=second; second->prev=ptr; }
return list;
}
void cJSONUtils_SortObject(cJSON *object) {object->child=cJSONUtils_SortList(object->child);}

View File

@ -1,13 +1,14 @@
#include "cJSON.h"
// Implement RFC6901 (https://tools.ietf.org/html/rfc6901) JSON Pointer spec.
/* Implement RFC6901 (https://tools.ietf.org/html/rfc6901) JSON Pointer spec. */
cJSON *cJSONUtils_GetPointer(cJSON *object,const char *pointer);
// Implement RFC6902 (https://tools.ietf.org/html/rfc6902) JSON Patch spec.
/* Implement RFC6902 (https://tools.ietf.org/html/rfc6902) JSON Patch spec. */
cJSON* cJSONUtils_GeneratePatches(cJSON *from,cJSON *to);
void cJSONUtils_AddPatchToArray(cJSON *array,const char *op,const char *path,cJSON *val); // Utility for generating patch array entries.
int cJSONUtils_ApplyPatches(cJSON *object,cJSON *patches); // Returns 0 for success.
void cJSONUtils_AddPatchToArray(cJSON *array,const char *op,const char *path,cJSON *val); /* Utility for generating patch array entries. */
int cJSONUtils_ApplyPatches(cJSON *object,cJSON *patches); /* Returns 0 for success. */
/*
// Note that ApplyPatches is NOT atomic on failure. To implement an atomic ApplyPatches, use:
//int cJSONUtils_AtomicApplyPatches(cJSON **object, cJSON *patches)
//{
@ -18,5 +19,8 @@ int cJSONUtils_ApplyPatches(cJSON *object,cJSON *patches); // Returns 0 for succ
// return error;
//}
// Code not added to library since this strategy is a LOT slower.
*/
char *cJSONUtils_FindPointerFromObjectTo(cJSON *object,cJSON *target); // Given a root object and a target object, construct a pointer from one to the other.
char *cJSONUtils_FindPointerFromObjectTo(cJSON *object,cJSON *target); /* Given a root object and a target object, construct a pointer from one to the other. */
void cJSONUtils_SortObject(cJSON *object); /* Sorts the members of the object into alphabetical order. */

View File

@ -5,7 +5,9 @@
int main()
{
// JSON Pointer tests:
int i;
/* JSON Pointer tests: */
cJSON *root;
const char *json="{"
"\"foo\": [\"bar\", \"baz\"],"
"\"\": 0,"
@ -21,17 +23,7 @@ int main()
const char *tests[12]={"","/foo","/foo/0","/","/a~1b","/c%d","/e^f","/g|h","/i\\j","/k\"l","/ ","/m~0n"};
printf("JSON Pointer Tests\n");
cJSON *root=cJSON_Parse(json);
for (int i=0;i<12;i++)
{
char *output=cJSON_Print(cJSONUtils_GetPointer(root,tests[i]));
printf("Test %d:\n%s\n\n",i+1,output);
free(output);
}
cJSON_Delete(root);
// JSON Apply Patch tests:
/* JSON Apply Patch tests: */
const char *patches[15][3]={
{"{ \"foo\": \"bar\"}", "[{ \"op\": \"add\", \"path\": \"/baz\", \"value\": \"qux\" }]","{\"baz\": \"qux\",\"foo\": \"bar\"}"},
{"{ \"foo\": [ \"bar\", \"baz\" ] }", "[{ \"op\": \"add\", \"path\": \"/foo/1\", \"value\": \"qux\" }]","{\"foo\": [ \"bar\", \"qux\", \"baz\" ] }"},
@ -49,8 +41,27 @@ int main()
{"{\"/\": 9,\"~1\": 10}","[{\"op\": \"test\", \"path\": \"/~01\", \"value\": \"10\"}]",""},
{"{ \"foo\": [\"bar\"] }","[ { \"op\": \"add\", \"path\": \"/foo/-\", \"value\": [\"abc\", \"def\"] }]","{\"foo\": [\"bar\", [\"abc\", \"def\"]] }"}};
/* Misc tests */
int numbers[10]={0,1,2,3,4,5,6,7,8,9};
const char *random="QWERTYUIOPASDFGHJKLZXCVBNM";
char buf[2]={0,0},*before,*after;
cJSON *object,*nums,*num6,*sortme;
printf("JSON Pointer Tests\n");
root=cJSON_Parse(json);
for (i=0;i<12;i++)
{
char *output=cJSON_Print(cJSONUtils_GetPointer(root,tests[i]));
printf("Test %d:\n%s\n\n",i+1,output);
free(output);
}
cJSON_Delete(root);
printf("JSON Apply Patch Tests\n");
for (int i=0;i<15;i++)
for (i=0;i<15;i++)
{
cJSON *object=cJSON_Parse(patches[i][0]);
cJSON *patch=cJSON_Parse(patches[i][1]);
@ -60,28 +71,39 @@ int main()
free(output);cJSON_Delete(object);cJSON_Delete(patch);
}
// JSON Generate Patch tests:
/* JSON Generate Patch tests: */
printf("JSON Generate Patch Tests\n");
for (int i=0;i<15;i++)
for (i=0;i<15;i++)
{
cJSON *from,*to,*patch;char *out;
if (!strlen(patches[i][2])) continue;
cJSON *from=cJSON_Parse(patches[i][0]);
cJSON *to=cJSON_Parse(patches[i][2]);
cJSON *patch=cJSONUtils_GeneratePatches(from,to);
char *out=cJSON_Print(patch);
from=cJSON_Parse(patches[i][0]);
to=cJSON_Parse(patches[i][2]);
patch=cJSONUtils_GeneratePatches(from,to);
out=cJSON_Print(patch);
printf("Test %d: (patch: %s):\n%s\n\n",i+1,patches[i][1],out);
free(out);cJSON_Delete(from);cJSON_Delete(to);cJSON_Delete(patch);
}
// Misc tests:
/* Misc tests: */
printf("JSON Pointer construct\n");
int numbers[10]={0,1,2,3,4,5,6,7,8,9};
cJSON *object=cJSON_CreateObject();
cJSON *nums=cJSON_CreateIntArray(numbers,10);
cJSON *num6=cJSON_GetArrayItem(nums,6);
object=cJSON_CreateObject();
nums=cJSON_CreateIntArray(numbers,10);
num6=cJSON_GetArrayItem(nums,6);
cJSON_AddItemToObject(object,"numbers",nums);
printf("Pointer: [%s]\n",cJSONUtils_FindPointerFromObjectTo(object,num6));
printf("Pointer: [%s]\n",cJSONUtils_FindPointerFromObjectTo(object,nums));
printf("Pointer: [%s]\n",cJSONUtils_FindPointerFromObjectTo(object,object));
/* JSON Sort test: */
sortme=cJSON_CreateObject();
for (i=0;i<26;i++)
{
buf[0]=random[i];cJSON_AddItemToObject(sortme,buf,cJSON_CreateNumber(1));
}
before=cJSON_Print(sortme);
cJSONUtils_SortObject(sortme);
after=cJSON_Print(sortme);
printf("Before: [%s]\nAfter: [%s]\n\n",before,after);
free(before);free(after);cJSON_Delete(sortme);
}