-
Notifications
You must be signed in to change notification settings - Fork 1
/
jsonify.c
410 lines (356 loc) · 8.34 KB
/
jsonify.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
/**
* Copyright (c) 2016 Tim Kuijsten
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#ifndef _XOPEN_SOURCE
#define _XOPEN_SOURCE 700
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "jsmn.h"
#define TOKENS 100000
#define MAXSTACK 10000
static int sp = 0;
static int stack[MAXSTACK];
static char closesym[MAXSTACK];
static char *out;
static size_t outsize;
static size_t outidx = 0;
/*
* Pop item from the stack.
*
* Return item from the stack on success or -1 if empty.
*/
static int
pop()
{
if (sp == 0)
return -1;
return stack[--sp];
}
/*
* Push new item on the stack, all ints except -1 can be pushed.
*/
static void
push(int val)
{
/* don't support -1 values, reserved for errors */
if (val == -1) {
fprintf(stderr, "can not push -1 to stack\n");
abort();
}
if (sp == MAXSTACK) {
fprintf(stderr, "can not push %d, stack full\n", val);
abort();
}
stack[sp++] = val;
}
static int
addout(char *src, size_t size)
{
if (outidx + size >= outsize)
return -1;
memcpy(out + outidx, src, size);
outidx += size;
out[outidx] = '\0';
return 0;
}
/*
* Run iterator on each token in tokens.
*
* If maxroots > 0, then at most this many root tokens (and it's children) will
* be parsed.
*
* Returns the index in tokens of the last parsed root token on success or -1
* on failure.
*/
static int
iterate(const char *src, jsmntok_t * tokens, int nrtokens, int maxroots,
int (*iterator)(jsmntok_t *, char *, int, int, char *))
{
char *key, *cp, c;
jsmntok_t *tok;
int i, j;
int depth, ndepth, roottokens, lastroottoken;
depth = 0;
ndepth = 0;
roottokens = 0;
lastroottoken = -1;
for (i = 0; i < nrtokens; i++) {
// consider each token at depth 0 a root
if (depth == 0) {
if (maxroots > 0 && maxroots == roottokens) {
return lastroottoken;
}
roottokens++;
lastroottoken = i;
}
tok = &tokens[i];
key = strndup(src + tok->start, tok->end - tok->start);
if (key == NULL)
abort();
switch (tok->type) {
case JSMN_OBJECT:
push('}');
ndepth++;
for (j = 0; j < tok->size - 1; j++)
push(',');
break;
case JSMN_ARRAY:
push(']');
ndepth++;
for (j = 0; j < tok->size - 1; j++)
push(',');
break;
case JSMN_UNDEFINED:
case JSMN_STRING:
case JSMN_PRIMITIVE:
break;
}
cp = closesym;
if (!tok->size) {
while ((c = pop()) == ']' || c == '}') {
ndepth--;
*cp++ = c;
}
}
*cp = '\0';
if (outidx < outsize) {
if (iterator(tok, key, depth, ndepth, closesym) < 0) {
free(key);
return -1;
}
} else {
free(key);
return -1;
}
depth = ndepth;
free(key);
}
return lastroottoken;
}
/*
* Convert json objects to contain two spaces per indent level and newlines
* after every key value pair or opening of a new object. Also sprinkle in some
* white space in arrays and don't quote keys.
*/
static int
human_readable_writer(jsmntok_t * tok, char *key, int depth, int ndepth,
char *closesym)
{
size_t i;
int j;
switch (tok->type) {
case JSMN_OBJECT:
addout("{", 1);
break;
case JSMN_ARRAY:
addout("[", 1);
break;
case JSMN_STRING:
if (tok->size) {/* this is a key */
addout("\n", 1);
/* indent with two spaces per next depth */
for (i = 0; i < (size_t) ndepth; i++)
addout(" ", 2);
addout(key, strlen(key));
addout(": ", 2);
} else { /* this is a value */
addout("\"", 1);
addout(key, strlen(key));
addout("\"", 1);
}
break;
case JSMN_UNDEFINED:
case JSMN_PRIMITIVE:
if (tok->size) {/* this is a key */
addout("\n", 1);
/* indent with two spaces per next depth */
for (i = 0; i < (size_t) ndepth; i++)
addout(" ", 2);
addout(key, strlen(key));
addout(": ", 2);
} else { /* this is a value */
addout(key, strlen(key));
}
break;
default:
fprintf(stderr, "unknown json token type: %d\n", tok->type);
abort();
}
for (i = 0; i < strlen(closesym); i++) {
/* indent with two spaces per depth */
if (closesym[i] == '}') {
if (ndepth < depth)
if (addout("\n", 1) < 0)
return -1;
for (j = 1; (size_t) j < depth - i; j++)
addout(" ", 2);
if (addout("}", 1) < 0)
return -1;
} else if (closesym[i] == ']') {
if (addout("]", 1) < 0)
return -1;
} else {
/* unknown character */
return -1;
}
}
/* if not increasing and not heading to the end of this root */
if (ndepth && depth >= ndepth)
if (!tok->size) /* and if not a key */
if (addout(",", 1) < 0)
return -1;
return 0;
}
static int
strict_writer(jsmntok_t * tok, char *key, int depth, int ndepth, char *closesym)
{
size_t keylen;
switch (tok->type) {
case JSMN_OBJECT:
addout("{", 1);
break;
case JSMN_ARRAY:
addout("[", 1);
break;
case JSMN_UNDEFINED:
if (tok->size) {/* quote keys */
addout("\"undefined\":", 11);
} else { /* don't quote values */
addout(key, strlen(key));
}
break;
case JSMN_STRING:
keylen = strlen(key);
addout("\"", 1);
addout(key, keylen);
addout("\"", 1);
if (tok->size) /* this is a key */
addout(":", 1);
break;
case JSMN_PRIMITIVE:
keylen = strlen(key);
/* convert single quotes at beginning and end of string */
if (key[0] == '\'')
key[0] = '"';
if (key[keylen - 1] == '\'')
key[keylen - 1] = '"';
if (tok->size) {/* quote keys */
addout("\"", 1);
addout(key, keylen);
addout("\":", 2);
} else /* don't quote values */
addout(key, keylen);
break;
default:
fprintf(stderr, "unknown json token type: %d\n", tok->type);
abort();
}
/* write any closing symbols */
if (addout(closesym, strlen(closesym)) < 0)
return -1;
/* if not increasing and not heading to the end of this root */
if (ndepth && depth >= ndepth)
if (!tok->size) /* and if not a key */
if (addout(",", 1) < 0)
return -1;
return 0;
}
/*
static void
print_tokens(const char *src, jsmntok_t *tokens, int nrtokens)
{
int i;
for (i = 0; i < nrtokens; i++)
printf("%2d T%d, s: %2d, e: %2d, nest: %d \"%.*s\"\n",
i,
tokens[i].type,
tokens[i].start,
tokens[i].end,
tokens[i].size,
tokens[i].end - tokens[i].start,
&src[tokens[i].start]);
}
*/
/*
* Create an indented representation of src with keys unescaped.
*
* Returns the number of bytes parsed in src on success, or -1 on error.
* On success, if dstsize > 0 a null byte is always written.
*/
int
human_readable(char *dst, size_t dstsize, const char *src, size_t srcsize)
{
jsmntok_t tokens[TOKENS];
jsmn_parser parser;
ssize_t nrtokens;
int r;
jsmn_init(&parser);
nrtokens = jsmn_parse(&parser, src, srcsize, tokens, TOKENS);
if (nrtokens < 0)
return -1;
if (nrtokens == 0) {
if (dstsize > 0)
dst[0] = '\0';
return 0;
}
if (dstsize < 1)
return -1;
out = dst;
outsize = dstsize;
out[0] = '\0';
outidx = 0;
r = iterate(src, tokens, nrtokens, 0, human_readable_writer);
if (r == -1)
return -1;
// return end of last processed root object token
return tokens[r].end + 1;
}
/*
* Add double quotes to keys that are unquoted by copying src into dst.
*
* Returns the number of bytes parsed in src on success, or -1 on error.
* On success, if dstsize > 0 a null byte is always written.
*/
int
relaxed_to_strict(char *dst, size_t dstsize, const char *src, size_t srcsize,
int maxobjects)
{
jsmntok_t tokens[TOKENS];
jsmn_parser parser;
ssize_t nrtokens;
int r;
jsmn_init(&parser);
nrtokens = jsmn_parse(&parser, src, srcsize, tokens, TOKENS);
if (nrtokens < 0)
return -1;
if (nrtokens == 0) {
if (dstsize > 0)
dst[0] = '\0';
return 0;
}
if (dstsize < 1)
return -1;
out = dst;
outsize = dstsize;
out[0] = '\0';
outidx = 0;
r = iterate(src, tokens, nrtokens, maxobjects, strict_writer);
if (r == -1)
return -1;
// return end of last processed root object token
return tokens[r].end + 1;
}