cheliequan
2023-01-13 db57152615104b4634c42946a912200a58bc5f93
util.cpp
@@ -234,3 +234,54 @@
    return bRet;
}
/*****************************************************************************
 函 数 名  : get_value_by_key
 功能描述  : 获取json字符串中字段为key值的value,pptr_data内存需要用户申请和释放
 输入参数  : char *json
             const char *key
             char **pptr_data
 输出参数  : 无
 返 回 值  :
 调用函数  :
 被调函数  :
 修改历史      :
  1.日    期   : 2023年1月13日
    作    者   : cheliequan
    修改内容   : 新生成函数
*****************************************************************************/
int get_value_by_key(char *json, const char *key, char **pptr_data)
{
    size_t data_len = 0;
    // Read JSON and get root
   yyjson_doc *doc = yyjson_read(json, strlen(json), 0);
   yyjson_val *root = yyjson_doc_get_root(doc);
   // Get root[key]
   yyjson_val *val = yyjson_obj_get(root, key);
   char * val_str = (char *)yyjson_get_str(val);
   printf("val: %s\n", val_str);
   if(NULL == val_str)
   {
      yyjson_doc_free(doc);
      return -1;
   }
   char *ptr_value = yyjson_val_write(val, YYJSON_WRITE_NOFLAG, &data_len);
   printf("data: %s\n", ptr_value);
   printf("len: %lu\n", data_len);
   *pptr_data = (char *)malloc(data_len);
   memset(*pptr_data, 0, data_len);
   memcpy(*pptr_data, ptr_value, data_len);
   // Free the doc
   yyjson_doc_free(doc);
   return 0;
}