kson.h 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #ifndef KSON_H
  2. #define KSON_H
  3. #include <string.h>
  4. #define KSON_TYPE_NO_QUOTE 1
  5. #define KSON_TYPE_SGL_QUOTE 2
  6. #define KSON_TYPE_DBL_QUOTE 3
  7. #define KSON_TYPE_BRACKET 4
  8. #define KSON_TYPE_BRACE 5
  9. #define KSON_OK 0
  10. #define KSON_ERR_EXTRA_LEFT 1
  11. #define KSON_ERR_EXTRA_RIGHT 2
  12. #define KSON_ERR_NO_KEY 3
  13. typedef struct kson_node_s {
  14. unsigned long long type:3, n:61;
  15. char *key;
  16. union {
  17. struct kson_node_s **child;
  18. char *str;
  19. } v;
  20. } kson_node_t;
  21. typedef struct {
  22. long n_nodes;
  23. kson_node_t *root;
  24. } kson_t;
  25. #ifdef __cplusplus
  26. extern "C" {
  27. #endif
  28. kson_t *kson_parse(const char *json);
  29. void kson_destroy(kson_t *kson);
  30. const kson_node_t *kson_by_path(const kson_node_t *root, int path_len, ...);
  31. void kson_format(const kson_node_t *root);
  32. #ifdef __cplusplus
  33. }
  34. #endif
  35. #define kson_is_internal(p) ((p)->type == KSON_TYPE_BRACKET || (p)->type == KSON_TYPE_BRACE)
  36. static inline const kson_node_t *kson_by_key(const kson_node_t *p, const char *key)
  37. {
  38. long i;
  39. if (!kson_is_internal(p)) return 0;
  40. for (i = 0; i < (long)p->n; ++i) {
  41. const kson_node_t *q = p->v.child[i];
  42. if (q->key && strcmp(q->key, key) == 0)
  43. return q;
  44. }
  45. return 0;
  46. }
  47. static inline const kson_node_t *kson_by_index(const kson_node_t *p, long i)
  48. {
  49. if (!kson_is_internal(p)) return 0;
  50. return 0 <= i && i < (long)p->n? p->v.child[i] : 0;
  51. }
  52. #endif