diff --git a/include/data/json.h b/include/data/json.h index ca6dd6e9f84..84ea2eb0c3d 100644 --- a/include/data/json.h +++ b/include/data/json.h @@ -654,6 +654,24 @@ ssize_t json_calc_encoded_len(const struct json_obj_descr *descr, int json_obj_encode_buf(const struct json_obj_descr *descr, size_t descr_len, const void *val, char *buffer, size_t buf_size); +/** + * @brief Encodes an array in a contiguous memory location + * + * @param descr Pointer to the descriptor array + * + * @param val Struct holding the values + * + * @param buffer Buffer to store the JSON data + * + * @param buf_size Size of buffer, in bytes, with space for the terminating + * NUL character + * + * @return 0 if object has been successfully encoded. A negative value + * indicates an error (as defined on errno.h). + */ +int json_arr_encode_buf(const struct json_obj_descr *descr, const void *val, + char *buffer, size_t buf_size); + /** * @brief Encodes an object using an arbitrary writer function * @@ -675,6 +693,24 @@ int json_obj_encode(const struct json_obj_descr *descr, size_t descr_len, const void *val, json_append_bytes_t append_bytes, void *data); +/** + * @brief Encodes an array using an arbitrary writer function + * + * @param descr Pointer to the descriptor array + * + * @param val Struct holding the values + * + * @param append_bytes Function to append bytes to the output + * + * @param data Data pointer to be passed to the append_bytes callback + * function. + * + * @return 0 if object has been successfully encoded. A negative value + * indicates an error. + */ +int json_arr_encode(const struct json_obj_descr *descr, const void *val, + json_append_bytes_t append_bytes, void *data); + #ifdef __cplusplus } #endif diff --git a/lib/os/json.c b/lib/os/json.c index 22808ca883c..30b4023159a 100644 --- a/lib/os/json.c +++ b/lib/os/json.c @@ -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;