xs_json.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  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. default:
  219. *t = JS_ERROR;
  220. break;
  221. }
  222. v = xs_utf8_insert(v, cp, &offset);
  223. }
  224. else {
  225. char cc = c;
  226. v = xs_insert_m(v, offset, &cc, 1);
  227. if (!xs_is_string(v)) {
  228. *t = JS_ERROR;
  229. break;
  230. }
  231. offset++;
  232. }
  233. }
  234. if (c == EOF)
  235. *t = JS_ERROR;
  236. }
  237. else
  238. if (c == '-' || (c >= '0' && c <= '9') || c == '.') {
  239. double d;
  240. ungetc(c, f);
  241. if (fscanf(f, "%lf", &d) == 1) {
  242. *t = JS_NUMBER;
  243. v = xs_number_new(d);
  244. }
  245. }
  246. else
  247. if (c == 't') {
  248. if (fgetc(f) == 'r' && fgetc(f) == 'u' && fgetc(f) == 'e') {
  249. *t = JS_TRUE;
  250. v = xs_val_new(XSTYPE_TRUE);
  251. }
  252. }
  253. else
  254. if (c == 'f') {
  255. if (fgetc(f) == 'a' && fgetc(f) == 'l' &&
  256. fgetc(f) == 's' && fgetc(f) == 'e') {
  257. *t = JS_FALSE;
  258. v = xs_val_new(XSTYPE_FALSE);
  259. }
  260. }
  261. else
  262. if (c == 'n') {
  263. if (fgetc(f) == 'u' && fgetc(f) == 'l' && fgetc(f) == 'l') {
  264. *t = JS_NULL;
  265. v = xs_val_new(XSTYPE_NULL);
  266. }
  267. }
  268. if (*t == JS_ERROR)
  269. v = xs_free(v);
  270. return v;
  271. }
  272. int xs_json_load_array_iter(FILE *f, xs_val **value, xstype *pt, int *c)
  273. /* loads the next scalar value from the JSON stream */
  274. /* if the value ahead is compound, value is NULL and pt is set */
  275. {
  276. js_type t;
  277. *value = _xs_json_load_lexer(f, &t);
  278. if (t == JS_ERROR)
  279. return -1;
  280. if (t == JS_CBRACK)
  281. return 0;
  282. if (*c > 0) {
  283. if (t == JS_COMMA)
  284. *value = _xs_json_load_lexer(f, &t);
  285. else
  286. return -1;
  287. }
  288. if (*value == NULL) {
  289. /* possible compound type ahead */
  290. if (t == JS_OBRACK)
  291. *pt = XSTYPE_LIST;
  292. else
  293. if (t == JS_OCURLY)
  294. *pt = XSTYPE_DICT;
  295. else
  296. return -1;
  297. }
  298. else
  299. *pt = xs_type(*value);
  300. *c = *c + 1;
  301. return 1;
  302. }
  303. int xs_json_load_array(FILE *f, int maxdepth, xs_list **l)
  304. /* loads a full JSON array (after the initial OBRACK) */
  305. /* l can be NULL for the content to be dropped */
  306. {
  307. xstype t;
  308. int r = 0;
  309. int c = 0;
  310. for (;;) {
  311. xs *v = NULL;
  312. r = xs_json_load_array_iter(f, &v, &t, &c);
  313. if (r == 1) {
  314. /* partial load? */
  315. if (v == NULL && maxdepth != 0) {
  316. if (t == XSTYPE_LIST) {
  317. if (l)
  318. v = xs_list_new();
  319. r = xs_json_load_array(f, maxdepth - 1, &v);
  320. }
  321. else
  322. if (t == XSTYPE_DICT) {
  323. if (l)
  324. v = xs_dict_new();
  325. r = xs_json_load_object(f, maxdepth - 1, &v);
  326. }
  327. }
  328. /* error? */
  329. if (r < 0)
  330. break;
  331. if (l)
  332. *l = xs_list_append(*l, v);
  333. }
  334. else
  335. break;
  336. }
  337. if (r < 0 && l)
  338. *l = xs_free(*l);
  339. return r;
  340. }
  341. int xs_json_load_object_iter(FILE *f, xs_str **key, xs_val **value, xstype *pt, int *c)
  342. /* loads the next key and scalar value from the JSON stream */
  343. /* if the value ahead is compound, value is NULL and pt is set */
  344. {
  345. js_type t;
  346. *key = _xs_json_load_lexer(f, &t);
  347. if (t == JS_ERROR)
  348. return -1;
  349. if (t == JS_CCURLY)
  350. return 0;
  351. if (*c > 0) {
  352. if (t == JS_COMMA)
  353. *key = _xs_json_load_lexer(f, &t);
  354. else
  355. return -1;
  356. }
  357. if (t != JS_STRING)
  358. return -1;
  359. xs_free(_xs_json_load_lexer(f, &t));
  360. if (t != JS_COLON)
  361. return -1;
  362. *value = _xs_json_load_lexer(f, &t);
  363. if (*value == NULL) {
  364. /* possible complex type ahead */
  365. if (t == JS_OBRACK)
  366. *pt = XSTYPE_LIST;
  367. else
  368. if (t == JS_OCURLY)
  369. *pt = XSTYPE_DICT;
  370. else
  371. return -1;
  372. }
  373. else
  374. *pt = xs_type(*value);
  375. *c = *c + 1;
  376. return 1;
  377. }
  378. int xs_json_load_object(FILE *f, int maxdepth, xs_dict **d)
  379. /* loads a full JSON object (after the initial OCURLY) */
  380. /* d can be NULL for the content to be dropped */
  381. {
  382. xstype t;
  383. int r = 0;
  384. int c = 0;
  385. for (;;) {
  386. xs *k = NULL;
  387. xs *v = NULL;
  388. r = xs_json_load_object_iter(f, &k, &v, &t, &c);
  389. if (r == 1) {
  390. /* partial load? */
  391. if (v == NULL && maxdepth != 0) {
  392. if (t == XSTYPE_LIST) {
  393. if (d)
  394. v = xs_list_new();
  395. r = xs_json_load_array(f, maxdepth - 1, &v);
  396. }
  397. else
  398. if (t == XSTYPE_DICT) {
  399. if (d)
  400. v = xs_dict_new();
  401. r = xs_json_load_object(f, maxdepth - 1, &v);
  402. }
  403. }
  404. /* error? */
  405. if (r < 0)
  406. break;
  407. if (d)
  408. *d = xs_dict_append(*d, k, v);
  409. }
  410. else
  411. break;
  412. }
  413. if (r < 0 && d)
  414. *d = xs_free(*d);
  415. return r;
  416. }
  417. xstype xs_json_load_type(FILE *f)
  418. /* identifies the type of a JSON stream */
  419. {
  420. xstype t = XSTYPE_NULL;
  421. js_type jt;
  422. xs_free(_xs_json_load_lexer(f, &jt));
  423. if (jt == JS_OBRACK)
  424. t = XSTYPE_LIST;
  425. else
  426. if (jt == JS_OCURLY)
  427. t = XSTYPE_DICT;
  428. return t;
  429. }
  430. xs_val *xs_json_load_full(FILE *f, int maxdepth)
  431. /* loads a JSON file */
  432. {
  433. xs_val *v = NULL;
  434. xstype t = xs_json_load_type(f);
  435. if (t == XSTYPE_LIST) {
  436. v = xs_list_new();
  437. xs_json_load_array(f, maxdepth, &v);
  438. }
  439. else
  440. if (t == XSTYPE_DICT) {
  441. v = xs_dict_new();
  442. xs_json_load_object(f, maxdepth, &v);
  443. }
  444. return v;
  445. }
  446. xs_val *xs_json_loads_full(const xs_str *json, int maxdepth)
  447. /* loads a string in JSON format and converts to a multiple data */
  448. {
  449. FILE *f;
  450. xs_val *v = NULL;
  451. if ((f = fmemopen((char *)json, strlen(json), "r")) != NULL) {
  452. v = xs_json_load_full(f, maxdepth);
  453. fclose(f);
  454. }
  455. return v;
  456. }
  457. #endif /* XS_IMPLEMENTATION */
  458. #endif /* _XS_JSON_H */