json: Add top-level array encoding support
The library supports the declaration of JSON arrays as both nested and top-level elements. However, as the provided encoding functions json_obj_encode() and json_obj_encode_buf() interpret all input structures as objects, top-level arrays are encoded as {"<field_name>":[{...},...,{...}]} instead of [{...},...,{...}]. Add new functions json_arr_encode() and json_arr_encode_buf() that enable top-level JSON array encoding. Signed-off-by: Markus Fuchs <markus.fuchs@de.sauter-bc.com>
This commit is contained in:
parent
a6786c54e0
commit
2f9b0d419b
2 changed files with 53 additions and 0 deletions
|
@ -865,6 +865,15 @@ int json_obj_encode(const struct json_obj_descr *descr, size_t descr_len,
|
|||
return append_bytes("}", 1, data);
|
||||
}
|
||||
|
||||
int json_arr_encode(const struct json_obj_descr *descr, const void *val,
|
||||
json_append_bytes_t append_bytes, void *data)
|
||||
{
|
||||
void *ptr = (char *)val + descr->offset;
|
||||
|
||||
return arr_encode(descr->array.element_descr, ptr, val, append_bytes,
|
||||
data);
|
||||
}
|
||||
|
||||
struct appender {
|
||||
char *buffer;
|
||||
size_t used;
|
||||
|
@ -895,6 +904,14 @@ int json_obj_encode_buf(const struct json_obj_descr *descr, size_t descr_len,
|
|||
&appender);
|
||||
}
|
||||
|
||||
int json_arr_encode_buf(const struct json_obj_descr *descr, const void *val,
|
||||
char *buffer, size_t buf_size)
|
||||
{
|
||||
struct appender appender = { .buffer = buffer, .size = buf_size };
|
||||
|
||||
return json_arr_encode(descr, val, append_bytes_to_buf, &appender);
|
||||
}
|
||||
|
||||
static int measure_bytes(const char *bytes, size_t len, void *data)
|
||||
{
|
||||
ssize_t *total = data;
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue