xs_json.h 12 KB

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