diff --git a/cJSON_Utils.c b/cJSON_Utils.c new file mode 100644 index 0000000..f5584d3 --- /dev/null +++ b/cJSON_Utils.c @@ -0,0 +1,43 @@ +#include +#include +#include +#include "cJSON_Utils.h" + +cJSON *cJSONUtils_GetPointer(cJSON *object,const char *pointer) +{ + cJSON *target=object;int which=0;const char *s=0;int len=0;char *element=0,*e=0; + + while (*pointer=='/' && object) + { + pointer++; + if (object->type==cJSON_Array) + { + which=0; + while (*pointer>='0' && *pointer<='9') {which*=10;which+=*pointer++ - '0';} + if (*pointer && *pointer!='/') return 0; + object=cJSON_GetArrayItem(object,which); + } + else if (object->type==cJSON_Object) + { + + s=pointer;len=0; + while (*s && *s!='/') {if (*s!='~') len++; s++;} + e=element=malloc(len+1); if (!element) return 0; + element[len]=0; + + while (*pointer && *pointer!='/') + { + if (*pointer=='~' && pointer[1]=='0') *e++='~',pointer+=2; + else if (*pointer=='~' && pointer[1]=='1') *e++='/',pointer+=2; + else if (*pointer=='~') {free(element); return 0;} // Invalid encoding. + else *e++=*pointer++; + } + object=cJSON_GetObjectItem(object,element); + free(element); + } + else return 0; + } + return object; +} + + diff --git a/cJSON_Utils.h b/cJSON_Utils.h new file mode 100644 index 0000000..3f7b0ce --- /dev/null +++ b/cJSON_Utils.h @@ -0,0 +1,5 @@ +#include "cJSON.h" + +// Implement RFC6901 (https://tools.ietf.org/html/rfc6901) JSON Pointer spec. +cJSON *cJSONUtils_GetPointer(cJSON *object,const char *pointer); + diff --git a/test_utils.c b/test_utils.c new file mode 100644 index 0000000..74d4a33 --- /dev/null +++ b/test_utils.c @@ -0,0 +1,30 @@ +#include +#include +#include "cJSON_Utils.h" + +int main() +{ + const char *json="{" + "\"foo\": [\"bar\", \"baz\"]," + "\"\": 0," + "\"a/b\": 1," + "\"c%d\": 2," + "\"e^f\": 3," + "\"g|h\": 4," + "\"i\\\\j\": 5," + "\"k\\\"l\": 6," + "\" \": 7," + "\"m~n\": 8" + "}"; + + 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++) + { + printf("Test %d:\n%s\n\n",i+1,cJSON_Print(cJSONUtils_GetPointer(root,tests[i]))); + } + + +}