James Kuszmaul | 82f6c04 | 2021-01-17 11:30:16 -0800 | [diff] [blame^] | 1 | /** |
| 2 | * @file json/encode.c JSON encoder |
| 3 | * |
| 4 | * Copyright (C) 2010 - 2015 Creytiv.com |
| 5 | */ |
| 6 | #include <re_types.h> |
| 7 | #include <re_fmt.h> |
| 8 | #include <re_list.h> |
| 9 | #include <re_odict.h> |
| 10 | #include <re_json.h> |
| 11 | |
| 12 | |
| 13 | static int encode_entry(struct re_printf *pf, const struct odict_entry *e) |
| 14 | { |
| 15 | struct odict *array; |
| 16 | struct le *le; |
| 17 | int err; |
| 18 | |
| 19 | if (!e) |
| 20 | return 0; |
| 21 | |
| 22 | switch (e->type) { |
| 23 | |
| 24 | case ODICT_OBJECT: |
| 25 | err = json_encode_odict(pf, e->u.odict); |
| 26 | break; |
| 27 | |
| 28 | case ODICT_ARRAY: |
| 29 | array = e->u.odict; |
| 30 | if (!array) |
| 31 | return 0; |
| 32 | |
| 33 | err = re_hprintf(pf, "["); |
| 34 | |
| 35 | for (le=array->lst.head; le; le=le->next) { |
| 36 | |
| 37 | const struct odict_entry *ae = le->data; |
| 38 | |
| 39 | err |= re_hprintf(pf, "%H%s", |
| 40 | encode_entry, ae, |
| 41 | le->next ? "," : ""); |
| 42 | } |
| 43 | |
| 44 | err |= re_hprintf(pf, "]"); |
| 45 | break; |
| 46 | |
| 47 | case ODICT_INT: |
| 48 | err = re_hprintf(pf, "%lld", e->u.integer); |
| 49 | break; |
| 50 | |
| 51 | case ODICT_DOUBLE: |
| 52 | err = re_hprintf(pf, "%f", e->u.dbl); |
| 53 | break; |
| 54 | |
| 55 | case ODICT_STRING: |
| 56 | err = re_hprintf(pf, "\"%H\"", utf8_encode, e->u.str); |
| 57 | break; |
| 58 | |
| 59 | case ODICT_BOOL: |
| 60 | err = re_hprintf(pf, "%s", e->u.boolean ? "true" : "false"); |
| 61 | break; |
| 62 | |
| 63 | case ODICT_NULL: |
| 64 | err = re_hprintf(pf, "null"); |
| 65 | break; |
| 66 | |
| 67 | default: |
| 68 | re_fprintf(stderr, "json: unsupported type %d\n", e->type); |
| 69 | err = EINVAL; |
| 70 | } |
| 71 | |
| 72 | return err; |
| 73 | } |
| 74 | |
| 75 | |
| 76 | int json_encode_odict(struct re_printf *pf, const struct odict *o) |
| 77 | { |
| 78 | struct le *le; |
| 79 | int err; |
| 80 | |
| 81 | if (!o) |
| 82 | return 0; |
| 83 | |
| 84 | err = re_hprintf(pf, "{"); |
| 85 | |
| 86 | for (le=o->lst.head; le; le=le->next) { |
| 87 | |
| 88 | const struct odict_entry *e = le->data; |
| 89 | |
| 90 | err |= re_hprintf(pf, "\"%H\":%H%s", |
| 91 | utf8_encode, e->key, |
| 92 | encode_entry, e, |
| 93 | le->next ? "," : ""); |
| 94 | } |
| 95 | |
| 96 | err |= re_hprintf(pf, "}"); |
| 97 | |
| 98 | return err; |
| 99 | } |