xs_json.h 12 KB

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