Skip to content

Commit 0066f21

Browse files
committed
add jsonwriter_set_option() and compact/pretty options
1 parent 3171db9 commit 0066f21

File tree

2 files changed

+28
-10
lines changed

2 files changed

+28
-10
lines changed

jsonwriter.c

Lines changed: 22 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,21 @@ struct jsonwriter_data {
2121
void *write_arg;
2222
char tmp[128]; // number buffer
2323
char just_wrote_key;
24+
char compact;
2425
};
2526

27+
void jsonwriter_set_option(jsonwriter_handle h, enum jsonwriter_option opt) {
28+
struct jsonwriter_data *data = h;
29+
switch(opt) {
30+
case jsonwriter_option_pretty:
31+
data->compact = 0;
32+
break;
33+
case jsonwriter_option_compact:
34+
data->compact = 1;
35+
break;
36+
}
37+
}
38+
2639
jsonwriter_handle jsonwriter_new(size_t (*write)(const void *, size_t, size_t, void *),
2740
void *write_arg) {
2841
struct jsonwriter_data *data = calloc(1, sizeof(*data));
@@ -41,15 +54,12 @@ void jsonwriter_delete(jsonwriter_handle h) {
4154
free(data->counts);
4255
}
4356

44-
/*
45-
static int jsonwriter_in_array(struct jsonwriter_data *data) {
46-
return data->close_brackets[data->depth] == ']';
47-
}
48-
*/
49-
5057
static int jsonwriter_indent(struct jsonwriter_data *data, char closing) {
5158
if(data->just_wrote_key) {
52-
data->write(": ", 1, 2, data->write_arg);
59+
if(data->compact)
60+
data->write(":", 1, 2, data->write_arg);
61+
else
62+
data->write(": ", 1, 2, data->write_arg);
5363
data->just_wrote_key = 0;
5464
return 0;
5565
}
@@ -62,9 +72,11 @@ static int jsonwriter_indent(struct jsonwriter_data *data, char closing) {
6272
}
6373
}
6474

65-
data->write("\n", 1, 1, data->write_arg);
66-
for(int d = data->depth; d > 0; d--)
67-
data->write(" ", 1, 2, data->write_arg);
75+
if(!data->compact) {
76+
data->write("\n", 1, 1, data->write_arg);
77+
for(int d = data->depth; d > 0; d--)
78+
data->write(" ", 1, 2, data->write_arg);
79+
}
6880
return 0;
6981
}
7082

jsonwriter.h

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,16 @@
77
extern "C" {
88
#endif
99

10+
enum jsonwriter_option {
11+
jsonwriter_option_pretty = 0,
12+
jsonwriter_option_compact = 1
13+
};
14+
1015
typedef void * jsonwriter_handle;
1116
jsonwriter_handle jsonwriter_new(size_t (*write)(const void *, size_t, size_t, void *),
1217
void *write_arg);
1318

19+
void jsonwriter_set_option(jsonwriter_handle h, enum jsonwriter_option opt);
1420
void jsonwriter_delete(jsonwriter_handle h);
1521

1622
int jsonwriter_start_object(jsonwriter_handle h);

0 commit comments

Comments
 (0)