Skip to content

Commit c0f5e20

Browse files
committed
add cJSON_Utils which includes JSON Pointer implementation
git-svn-id: svn://svn.code.sf.net/p/cjson/code@63 e3330c51-1366-4df0-8b21-3ccf24e3d50e
1 parent 2abfb71 commit c0f5e20

3 files changed

Lines changed: 78 additions & 0 deletions

File tree

‎cJSON_Utils.c‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
#include <string.h>
4+
#include "cJSON_Utils.h"
5+
6+
cJSON *cJSONUtils_GetPointer(cJSON *object,const char *pointer)
7+
{
8+
cJSON *target=object;int which=0;const char *s=0;int len=0;char *element=0,*e=0;
9+
10+
while (*pointer=='/' && object)
11+
{
12+
pointer++;
13+
if (object->type==cJSON_Array)
14+
{
15+
which=0;
16+
while (*pointer>='0' && *pointer<='9') {which*=10;which+=*pointer++ - '0';}
17+
if (*pointer && *pointer!='/') return 0;
18+
object=cJSON_GetArrayItem(object,which);
19+
}
20+
else if (object->type==cJSON_Object)
21+
{
22+
23+
s=pointer;len=0;
24+
while (*s && *s!='/') {if (*s!='~') len++; s++;}
25+
e=element=malloc(len+1); if (!element) return 0;
26+
element[len]=0;
27+
28+
while (*pointer && *pointer!='/')
29+
{
30+
if (*pointer=='~' && pointer[1]=='0') *e++='~',pointer+=2;
31+
else if (*pointer=='~' && pointer[1]=='1') *e++='/',pointer+=2;
32+
else if (*pointer=='~') {free(element); return 0;} // Invalid encoding.
33+
else *e++=*pointer++;
34+
}
35+
object=cJSON_GetObjectItem(object,element);
36+
free(element);
37+
}
38+
else return 0;
39+
}
40+
return object;
41+
}
42+
43+

‎cJSON_Utils.h‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
#include "cJSON.h"
2+
3+
// Implement RFC6901 (https://tools.ietf.org/html/rfc6901) JSON Pointer spec.
4+
cJSON *cJSONUtils_GetPointer(cJSON *object,const char *pointer);
5+

‎test_utils.c‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
#include <stdlib.h>
2+
#include <stdio.h>
3+
#include "cJSON_Utils.h"
4+
5+
int main()
6+
{
7+
const char *json="{"
8+
"\"foo\": [\"bar\", \"baz\"],"
9+
"\"\": 0,"
10+
"\"a/b\": 1,"
11+
"\"c%d\": 2,"
12+
"\"e^f\": 3,"
13+
"\"g|h\": 4,"
14+
"\"i\\\\j\": 5,"
15+
"\"k\\\"l\": 6,"
16+
"\" \": 7,"
17+
"\"m~n\": 8"
18+
"}";
19+
20+
const char *tests[12]={"","/foo","/foo/0","/","/a~1b","/c%d","/e^f","/g|h","/i\\j","/k\"l","/ ","/m~0n"};
21+
22+
printf("JSON Pointer Tests\n");
23+
cJSON *root=cJSON_Parse(json);
24+
for (int i=0;i<12;i++)
25+
{
26+
printf("Test %d:\n%s\n\n",i+1,cJSON_Print(cJSONUtils_GetPointer(root,tests[i])));
27+
}
28+
29+
30+
}

0 commit comments

Comments
 (0)