xs_json.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  1. /* copyright (c) 2022 - 2026 grunfink et al. / MIT license */
  2. #ifndef _XS_JSON_H
  3. #define _XS_JSON_H
  4. #ifndef MAX_JSON_DEPTH
  5. #define MAX_JSON_DEPTH 32
  6. #endif
  7. void xs_json_dump_value(const xs_val *data, int level, int indent, FILE *f);
  8. int xs_json_dump(const xs_val *data, int indent, FILE *f);
  9. xs_str *xs_json_dumps(const xs_val *data, int indent);
  10. xs_val *xs_json_load_full(FILE *f, int maxdepth);
  11. xs_val *xs_json_loads_full(const xs_str *json, int maxdepth);
  12. #define xs_json_load(f) xs_json_load_full(f, MAX_JSON_DEPTH)
  13. #define xs_json_loads(s) xs_json_loads_full(s, MAX_JSON_DEPTH)
  14. xstype xs_json_load_type(FILE *f);
  15. int xs_json_load_array_iter(FILE *f, xs_val **value, xstype *pt, int *c);
  16. int xs_json_load_object_iter(FILE *f, xs_str **key, xs_val **value, xstype *pt, int *c);
  17. int xs_json_load_array(FILE *f, int maxdepth, xs_list **l);
  18. int xs_json_load_object(FILE *f, int maxdepth, xs_dict **d);
  19. #ifdef XS_IMPLEMENTATION
  20. /** IMPLEMENTATION **/
  21. #include "xs_unicode.h"
  22. /** JSON dumps **/
  23. static void _xs_json_dump_str(const char *data, FILE *f)
  24. /* dumps a string in JSON format */
  25. {
  26. unsigned char c;
  27. fputs("\"", f);
  28. while ((c = *data)) {
  29. if (c == '\n')
  30. fputs("\\n", f);
  31. else
  32. if (c == '\r')
  33. fputs("\\r", f);
  34. else
  35. if (c == '\t')
  36. fputs("\\t", f);
  37. else
  38. if (c == '\\')
  39. fputs("\\\\", f);
  40. else
  41. if (c == '"')
  42. fputs("\\\"", f);
  43. else
  44. if (c < 32)
  45. fprintf(f, "\\u%04x", (unsigned int) c);
  46. else
  47. fputc(c, f);
  48. data++;
  49. }
  50. fputs("\"", f);
  51. }
  52. static void _xs_json_indent(int level, int indent, FILE *f)
  53. /* adds indentation */
  54. {
  55. if (indent) {
  56. int n;
  57. fputc('\n', f);
  58. for (n = 0; n < level * indent; n++)
  59. fputc(' ', f);
  60. }
  61. }
  62. void xs_json_dump_value(const xs_val *data, int level, int indent, FILE *f)
  63. /* dumps partial data as JSON */
  64. {
  65. int c = 0;
  66. const xs_val *v;
  67. switch (xs_type(data)) {
  68. case XSTYPE_NULL:
  69. fputs("null", f);
  70. break;
  71. case XSTYPE_TRUE:
  72. fputs("true", f);
  73. break;
  74. case XSTYPE_FALSE:
  75. fputs("false", f);
  76. break;
  77. case XSTYPE_NUMBER:
  78. fputs(xs_number_str(data), f);
  79. break;
  80. case XSTYPE_LIST:
  81. fputc('[', f);
  82. xs_list_foreach(data, v) {
  83. if (c != 0)
  84. fputc(',', f);
  85. _xs_json_indent(level + 1, indent, f);
  86. xs_json_dump_value(v, level + 1, indent, f);
  87. c++;
  88. }
  89. _xs_json_indent(level, indent, f);
  90. fputc(']', f);
  91. break;
  92. case XSTYPE_DICT:
  93. fputc('{', f);
  94. const xs_str *k;
  95. xs_dict_foreach(data, k, v) {
  96. if (c != 0)
  97. fputc(',', f);
  98. _xs_json_indent(level + 1, indent, f);
  99. _xs_json_dump_str(k, f);
  100. fputc(':', f);
  101. if (indent)
  102. fputc(' ', f);
  103. xs_json_dump_value(v, level + 1, indent, f);
  104. c++;
  105. }
  106. _xs_json_indent(level, indent, f);
  107. fputc('}', f);
  108. break;
  109. case XSTYPE_STRING:
  110. _xs_json_dump_str(data, f);
  111. break;
  112. default:
  113. break;
  114. }
  115. }
  116. int xs_json_dump(const xs_val *data, int indent, FILE *f)
  117. /* dumps data into a file as JSON */
  118. {
  119. xstype t = xs_type(data);
  120. if (t == XSTYPE_LIST || t == XSTYPE_DICT) {
  121. xs_json_dump_value(data, 0, indent, f);
  122. return 1;
  123. }
  124. return 0;
  125. }
  126. xs_str *xs_json_dumps(const xs_val *data, int indent)
  127. /* dumps data as a JSON string */
  128. {
  129. xs_str *s = NULL;
  130. size_t sz;
  131. FILE *f;
  132. if ((f = open_memstream(&s, &sz)) != NULL) {
  133. int r = xs_json_dump(data, indent, f);
  134. fclose(f);
  135. if (!r)
  136. s = xs_free(s);
  137. }
  138. return s;
  139. }
  140. /** JSON loads **/
  141. typedef enum {
  142. JS_ERROR = -1,
  143. JS_INCOMPLETE,
  144. JS_OCURLY,
  145. JS_OBRACK,
  146. JS_CCURLY,
  147. JS_CBRACK,
  148. JS_COMMA,
  149. JS_COLON,
  150. JS_VALUE,
  151. JS_STRING,
  152. JS_NUMBER,
  153. JS_TRUE,
  154. JS_FALSE,
  155. JS_NULL,
  156. JS_ARRAY,
  157. JS_OBJECT
  158. } js_type;
  159. static xs_val *_xs_json_load_lexer(FILE *f, js_type *t)
  160. {
  161. int c;
  162. xs_val *v = NULL;
  163. int offset;
  164. *t = JS_ERROR;
  165. /* skip blanks */
  166. while ((c = fgetc(f)) == ' ' || c == '\t' || c == '\n' || c == '\r');
  167. if (c == '{')
  168. *t = JS_OCURLY;
  169. else
  170. if (c == '}')
  171. *t = JS_CCURLY;
  172. else
  173. if (c == '[')
  174. *t = JS_OBRACK;
  175. else
  176. if (c == ']')
  177. *t = JS_CBRACK;
  178. else
  179. if (c == ',')
  180. *t = JS_COMMA;
  181. else
  182. if (c == ':')
  183. *t = JS_COLON;
  184. else
  185. if (c == '"') {
  186. *t = JS_STRING;
  187. v = xs_str_new(NULL);
  188. offset = 0;
  189. while ((c = fgetc(f)) != '"' && c != EOF && *t != JS_ERROR) {
  190. if (c == '\\') {
  191. unsigned int cp = fgetc(f);
  192. switch (cp) {
  193. case 'n': cp = '\n'; break;
  194. case 'r': cp = '\r'; break;
  195. case 't': cp = '\t'; break;
  196. case 'u': /* Unicode codepoint as an hex char */
  197. if (fscanf(f, "%04x", &cp) != 1) {
  198. *t = JS_ERROR;
  199. break;
  200. }
  201. if (xs_is_surrogate(cp)) {
  202. /* \u must follow */
  203. if (fgetc(f) != '\\' || fgetc(f) != 'u') {
  204. *t = JS_ERROR;
  205. break;
  206. }
  207. unsigned int p2;
  208. if (fscanf(f, "%04x", &p2) != 1) {
  209. *t = JS_ERROR;
  210. break;
  211. }
  212. cp = xs_surrogate_dec(cp, p2);
  213. }
  214. /* replace dangerous control codes with their visual representations */
  215. if (cp < ' ' && !strchr("\r\n\t", cp))
  216. cp += 0x2400;
  217. break;
  218. }
  219. v = xs_utf8_insert(v, cp, &offset);
  220. }
  221. else {
  222. char cc = c;
  223. v = xs_insert_m(v, offset, &cc, 1);
  224. if (!xs_is_string(v)) {
  225. *t = JS_ERROR;
  226. break;
  227. }
  228. offset++;
  229. }
  230. }
  231. if (c == EOF)
  232. *t = JS_ERROR;
  233. }
  234. else
  235. if (c == '-' || (c >= '0' && c <= '9') || c == '.') {
  236. double d;
  237. ungetc(c, f);
  238. if (fscanf(f, "%lf", &d) == 1) {
  239. *t = JS_NUMBER;
  240. v = xs_number_new(d);
  241. }
  242. }
  243. else
  244. if (c == 't') {
  245. if (fgetc(f) == 'r' && fgetc(f) == 'u' && fgetc(f) == 'e') {
  246. *t = JS_TRUE;
  247. v = xs_val_new(XSTYPE_TRUE);
  248. }
  249. }
  250. else
  251. if (c == 'f') {
  252. if (fgetc(f) == 'a' && fgetc(f) == 'l' &&
  253. fgetc(f) == 's' && fgetc(f) == 'e') {
  254. *t = JS_FALSE;
  255. v = xs_val_new(XSTYPE_FALSE);
  256. }
  257. }
  258. else
  259. if (c == 'n') {
  260. if (fgetc(f) == 'u' && fgetc(f) == 'l' && fgetc(f) == 'l') {
  261. *t = JS_NULL;
  262. v = xs_val_new(XSTYPE_NULL);
  263. }
  264. }
  265. if (*t == JS_ERROR)
  266. v = xs_free(v);
  267. return v;
  268. }
  269. int xs_json_load_array_iter(FILE *f, xs_val **value, xstype *pt, int *c)
  270. /* loads the next scalar value from the JSON stream */
  271. /* if the value ahead is compound, value is NULL and pt is set */
  272. {
  273. js_type t;
  274. *value = _xs_json_load_lexer(f, &t);
  275. if (t == JS_ERROR)
  276. return -1;
  277. if (t == JS_CBRACK)
  278. return 0;
  279. if (*c > 0) {
  280. if (t == JS_COMMA)
  281. *value = _xs_json_load_lexer(f, &t);
  282. else
  283. return -1;
  284. }
  285. if (*value == NULL) {
  286. /* possible compound type ahead */
  287. if (t == JS_OBRACK)
  288. *pt = XSTYPE_LIST;
  289. else
  290. if (t == JS_OCURLY)
  291. *pt = XSTYPE_DICT;
  292. else
  293. return -1;
  294. }
  295. else
  296. *pt = xs_type(*value);
  297. *c = *c + 1;
  298. return 1;
  299. }
  300. int xs_json_load_array(FILE *f, int maxdepth, xs_list **l)
  301. /* loads a full JSON array (after the initial OBRACK) */
  302. /* l can be NULL for the content to be dropped */
  303. {
  304. xstype t;
  305. int r = 0;
  306. int c = 0;
  307. for (;;) {
  308. xs *v = NULL;
  309. r = xs_json_load_array_iter(f, &v, &t, &c);
  310. if (r == 1) {
  311. /* partial load? */
  312. if (v == NULL && maxdepth != 0) {
  313. if (t == XSTYPE_LIST) {
  314. if (l)
  315. v = xs_list_new();
  316. r = xs_json_load_array(f, maxdepth - 1, &v);
  317. }
  318. else
  319. if (t == XSTYPE_DICT) {
  320. if (l)
  321. v = xs_dict_new();
  322. r = xs_json_load_object(f, maxdepth - 1, &v);
  323. }
  324. }
  325. /* error? */
  326. if (r < 0)
  327. break;
  328. if (l)
  329. *l = xs_list_append(*l, v);
  330. }
  331. else
  332. break;
  333. }
  334. if (r < 0 && l)
  335. *l = xs_free(*l);
  336. return r;
  337. }
  338. int xs_json_load_object_iter(FILE *f, xs_str **key, xs_val **value, xstype *pt, int *c)
  339. /* loads the next key and scalar value from the JSON stream */
  340. /* if the value ahead is compound, value is NULL and pt is set */
  341. {
  342. js_type t;
  343. *key = _xs_json_load_lexer(f, &t);
  344. if (t == JS_ERROR)
  345. return -1;
  346. if (t == JS_CCURLY)
  347. return 0;
  348. if (*c > 0) {
  349. if (t == JS_COMMA)
  350. *key = _xs_json_load_lexer(f, &t);
  351. else
  352. return -1;
  353. }
  354. if (t != JS_STRING)
  355. return -1;
  356. xs_free(_xs_json_load_lexer(f, &t));
  357. if (t != JS_COLON)
  358. return -1;
  359. *value = _xs_json_load_lexer(f, &t);
  360. if (*value == NULL) {
  361. /* possible complex type ahead */
  362. if (t == JS_OBRACK)
  363. *pt = XSTYPE_LIST;
  364. else
  365. if (t == JS_OCURLY)
  366. *pt = XSTYPE_DICT;
  367. else
  368. return -1;
  369. }
  370. else
  371. *pt = xs_type(*value);
  372. *c = *c + 1;
  373. return 1;
  374. }
  375. int xs_json_load_object(FILE *f, int maxdepth, xs_dict **d)
  376. /* loads a full JSON object (after the initial OCURLY) */
  377. /* d can be NULL for the content to be dropped */
  378. {
  379. xstype t;
  380. int r = 0;
  381. int c = 0;
  382. for (;;) {
  383. xs *k = NULL;
  384. xs *v = NULL;
  385. r = xs_json_load_object_iter(f, &k, &v, &t, &c);
  386. if (r == 1) {
  387. /* partial load? */
  388. if (v == NULL && maxdepth != 0) {
  389. if (t == XSTYPE_LIST) {
  390. if (d)
  391. v = xs_list_new();
  392. r = xs_json_load_array(f, maxdepth - 1, &v);
  393. }
  394. else
  395. if (t == XSTYPE_DICT) {
  396. if (d)
  397. v = xs_dict_new();
  398. r = xs_json_load_object(f, maxdepth - 1, &v);
  399. }
  400. }
  401. /* error? */
  402. if (r < 0)
  403. break;
  404. if (d)
  405. *d = xs_dict_append(*d, k, v);
  406. }
  407. else
  408. break;
  409. }
  410. if (r < 0 && d)
  411. *d = xs_free(*d);
  412. return r;
  413. }
  414. xstype xs_json_load_type(FILE *f)
  415. /* identifies the type of a JSON stream */
  416. {
  417. xstype t = XSTYPE_NULL;
  418. js_type jt;
  419. xs_free(_xs_json_load_lexer(f, &jt));
  420. if (jt == JS_OBRACK)
  421. t = XSTYPE_LIST;
  422. else
  423. if (jt == JS_OCURLY)
  424. t = XSTYPE_DICT;
  425. return t;
  426. }
  427. xs_val *xs_json_load_full(FILE *f, int maxdepth)
  428. /* loads a JSON file */
  429. {
  430. xs_val *v = NULL;
  431. xstype t = xs_json_load_type(f);
  432. if (t == XSTYPE_LIST) {
  433. v = xs_list_new();
  434. xs_json_load_array(f, maxdepth, &v);
  435. }
  436. else
  437. if (t == XSTYPE_DICT) {
  438. v = xs_dict_new();
  439. xs_json_load_object(f, maxdepth, &v);
  440. }
  441. return v;
  442. }
  443. xs_val *xs_json_loads_full(const xs_str *json, int maxdepth)
  444. /* loads a string in JSON format and converts to a multiple data */
  445. {
  446. FILE *f;
  447. xs_val *v = NULL;
  448. if ((f = fmemopen((char *)json, strlen(json), "r")) != NULL) {
  449. v = xs_json_load_full(f, maxdepth);
  450. fclose(f);
  451. }
  452. return v;
  453. }
  454. #endif /* XS_IMPLEMENTATION */
  455. #endif /* _XS_JSON_H */