-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathescape-json-string.c
87 lines (78 loc) · 1.31 KB
/
escape-json-string.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
/*
* Synopsis:
* Escape a json string read on standard input.
* Usage:
* JSON=$(echo 'hello, world' | escape-json-string)
* Exit Status:
* 0 ok
* 1 failed
* Note:
* Non ascii are not escaped properly!
*
* What about escaping command line arguments?
*
* Is code safe for UTF-8?
*/
#include <sys/errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "jmscott/libjmscott.h"
extern int errno;
char *jmscott_progname = "escape-json-string";
static void
die(char *msg)
{
int eno = errno;
if (eno > 0)
jmscott_die2(1, msg, strerror(eno));
jmscott_die(1 , msg);
}
int
main(int argc, char **argv)
{
int c;
(void)argv;
errno = 0;
if (argc != 1)
die("wrong number of cli arguments");
while ((c = getchar()) != EOF) {
if (ferror(stdin))
die("getchar(stdin) failed");
switch (c) {
case '\b':
putchar('\\');
putchar('b');
break;
case '\f':
putchar('\\');
putchar('f');
break;
case '\n':
putchar('\\');
putchar('n');
break;
case '\r':
putchar('\\');
putchar('r');
break;
case '\t':
putchar('\\');
putchar('t');
break;
case '"':
putchar('\\');
putchar('"');
break;
case '\\':
putchar('\\');
putchar('\\');
break;
default:
putchar(c);
}
if (ferror(stdout))
die("putchar(stdout) failed");
}
exit(0);
}