diff --git a/src/libjson/json_utils.c b/src/libjson/json_utils.c index 1db71a8..50c9085 100755 --- a/src/libjson/json_utils.c +++ b/src/libjson/json_utils.c @@ -238,7 +238,45 @@ char* obi_add_comment(char* comments, const char* key, const char* value) // Free structure cJSON_Delete(comments_struct); + return new_comments; } +char* obi_read_comment(char* comments, const char* key) +{ + cJSON* comments_struct = NULL; + cJSON* value_json = NULL; + char* value = NULL; + + comments_struct = cJSON_Parse(comments); + if (comments_struct == NULL) + { + obi_set_errno(OBI_JSON_ERROR); + obidebug(1, "\nError parsing the comments when reading comments, key: %s", key); + return NULL; + } + + value_json = cJSON_GetObjectItem(comments_struct, key); + if (value_json == NULL) + { + obi_set_errno(OBI_JSON_ERROR); + obidebug(1, "\nError getting a value when reading a comment, key: %s", key); + return NULL; + } + + value = cJSON_Print(value_json); + if (value == NULL) + { + obi_set_errno(OBI_JSON_ERROR); + obidebug(1, "\nError formatting a value when reading a comment, key: %s", key); + return NULL; + } + + // Free structure + cJSON_Delete(comments_struct); + + return value; +} + + diff --git a/src/libjson/json_utils.h b/src/libjson/json_utils.h index f29e8a0..9031078 100755 --- a/src/libjson/json_utils.h +++ b/src/libjson/json_utils.h @@ -21,6 +21,9 @@ /** * @brief Add a comment (in the key/value form) to a (JSON formatted) comments character string. * + * Note: The usual way to use this function is to call obi_add_comment() with a view or a column's comments, + * then obi_view_write_comments() with the result, then free said result. + * * @warning If the key is already in the structure, its associated value is turned * into an array if needed and the new value is added to that array. * // TODO discuss replace boolean @@ -40,4 +43,23 @@ char* obi_add_comment(char* comments, const char* key, const char* value); +/** + * @brief Read a comment (returns its value) from a (JSON formatted) comments character string. + * + * @warning The returned character string is framed with "". // TODO which sucks + * + * @warning The returned pointer has to be freed by the caller. + * + * @param comments The initial comments, in the form of a JSON formatted character string. + * @param key The key referring to the wanted value. + * + * @returns A pointer on the character string containing the formatted value, framed with "". + * @retval NULL if an error occurred. + * + * @since August 2019 + * @author Celine Mercier (celine.mercier@metabarcoding.org) + */ +char* obi_read_comment(char* comments, const char* key); + + #endif /* JSON_UTILS_H_ */