json_encode_str.c: encode string to JSON string - randomcrap - random crap programs of varying quality
(HTM) git clone git://git.codemadness.org/randomcrap
(DIR) Log
(DIR) Files
(DIR) Refs
(DIR) README
(DIR) LICENSE
---
(DIR) commit 836d5914004bba2b59ec8f6813738c8823009111
(DIR) parent acd5fa4e7eccb08b803d30e6ef8df3a522a7a1b2
(HTM) Author: Hiltjo Posthuma <hiltjo@codemadness.org>
Date: Sun, 10 Aug 2025 19:15:56 +0200
json_encode_str.c: encode string to JSON string
Diffstat:
A json_encode_str.c | 60 +++++++++++++++++++++++++++++++
1 file changed, 60 insertions(+), 0 deletions(-)
---
(DIR) diff --git a/json_encode_str.c b/json_encode_str.c
@@ -0,0 +1,60 @@
+/* encode string to JSON string */
+
+#include <stdio.h>
+
+static int
+digit2hex(int c)
+{
+ if (c >= 0 && c <= 9)
+ return c + '0';
+ else if (c >= 10 && c <= 15)
+ return (c - 10) + 'a';
+ return 0;
+}
+
+int
+main(void)
+{
+ int c;
+
+ putchar('"');
+
+ while ((c = getchar()) != EOF) {
+ switch (c) {
+ case '"':
+ case '\\':
+ putchar('\\');
+ putchar(c);
+ continue;
+ }
+
+ switch (c) {
+ case '\b': putchar('\\'); putchar('b'); continue;
+ case '\f': putchar('\\'); putchar('f'); continue;
+ case '\n': putchar('\\'); putchar('n'); continue;
+ case '\r': putchar('\\'); putchar('r'); continue;
+ case '\t': putchar('\\'); putchar('t'); continue;
+ default:
+ if (c < 0x20) {
+ putchar('\\');
+ putchar('u');
+ putchar('0');
+ putchar('0');
+ putchar(digit2hex((c >> 4)));
+ putchar(digit2hex(c & 0x0f));
+ continue;
+ }
+ break;
+ }
+ putchar(c);
+ }
+
+ putchar('"');
+
+ if (ferror(stdin) || fflush(stdout) || ferror(stdout)) {
+ perror(NULL);
+ return 1;
+ }
+
+ return 0;
+}