in src/map.c [604:700]
STRING_HANDLE Map_ToJSON(MAP_HANDLE handle)
{
STRING_HANDLE result;
/*Codes_SRS_MAP_02_052: [If parameter handle is NULL then Map_ToJSON shall return NULL.] */
if (handle == NULL)
{
/*Codes_SRS_MAP_02_051: [If any error occurs while producing the output, then Map_ToJSON shall fail and return NULL.] */
result = NULL;
LogError("invalid arg (NULL)");
}
else
{
/*Codes_SRS_MAP_02_048: [Map_ToJSON shall produce a STRING_HANDLE representing the content of the MAP.] */
result = STRING_construct("{");
if (result == NULL)
{
/*Codes_SRS_MAP_02_051: [If any error occurs while producing the output, then Map_ToJSON shall fail and return NULL.] */
LogError("STRING_construct failed");
}
else
{
size_t i;
MAP_HANDLE_DATA* handleData = handle;
/*Codes_SRS_MAP_02_049: [If the MAP is empty, then Map_ToJSON shall produce the string "{}".*/
bool breakFor = false; /*used to break out of for*/
for (i = 0; (i < handleData->count) && (!breakFor); i++)
{
/*add one entry to the JSON*/
/*Codes_SRS_MAP_02_050: [If the map has properties then Map_ToJSON shall produce the following string:{"name1":"value1", "name2":"value2" ...}]*/
STRING_HANDLE key = STRING_new_JSON(handleData->keys[i]);
if (key == NULL)
{
/*Codes_SRS_MAP_02_051: [If any error occurs while producing the output, then Map_ToJSON shall fail and return NULL.] */
LogError("STRING_new_JSON failed");
STRING_delete(result);
result = NULL;
breakFor = true;
}
else
{
STRING_HANDLE value = STRING_new_JSON(handleData->values[i]);
if (value == NULL)
{
/*Codes_SRS_MAP_02_051: [If any error occurs while producing the output, then Map_ToJSON shall fail and return NULL.] */
LogError("STRING_new_JSON failed");
STRING_delete(result);
result = NULL;
breakFor = true;
}
else
{
if (!(
((i>0) ? (STRING_concat(result, ",") == 0) : 1) &&
(STRING_concat_with_STRING(result, key) == 0) &&
(STRING_concat(result, ":") == 0) &&
(STRING_concat_with_STRING(result, value) == 0)
))
{
/*Codes_SRS_MAP_02_051: [If any error occurs while producing the output, then Map_ToJSON shall fail and return NULL.] */
LogError("failed to build the JSON");
STRING_delete(result);
result = NULL;
breakFor = true;
}
else
{
/*all nice, go to the next element in the map*/
}
STRING_delete(value);
}
STRING_delete(key);
}
}
if (breakFor)
{
LogError("error happened during JSON string builder");
}
else
{
if (STRING_concat(result, "}") != 0)
{
/*Codes_SRS_MAP_02_051: [If any error occurs while producing the output, then Map_ToJSON shall fail and return NULL.] */
LogError("failed to build the JSON");
STRING_delete(result);
result = NULL;
}
else
{
/*return as is, JSON has been build*/
}
}
}
}
return result;
}