Skip to content

Commit caf9c12

Browse files
committed
[utils] Add method to convert dict-like vectors of strings to maps
The function takes a dictionary (Python-like or a flat JSON file content) represented as a flat vector of strings that contain key-value pairs into a map of pairs of strings.
1 parent 977d931 commit caf9c12

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

src/aliceVision/utils/convert.hpp

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
#pragma once
88

99
#include <iomanip>
10+
#include <map>
1011
#include <sstream>
1112
#include <string>
1213

@@ -20,5 +21,53 @@ inline std::string toStringZeroPadded(std::size_t i, std::size_t zeroPadding)
2021
return ss.str();
2122
}
2223

24+
/**
25+
* @brief Converts a flat vector of strings representing key-value pairs
26+
* into a std::map of string-to-string.
27+
*
28+
* @param dict A vector of strings where each pair of elements (i, i+1)
29+
* represents a key and value, possibly with formatting characters.
30+
* @return std::map<std::string, std::string> A map containing cleaned key-value pairs.
31+
*
32+
* @code
33+
* std::vector<std::string> dict = {"{key1:", "value1,", "key2:", "value2}"};
34+
* auto result = dictStringToStringMap(dict);
35+
* // result => { {"key1", "value1"}, {"key2", "value2"} }
36+
* @endcode
37+
*/
38+
inline std::map<std::string, std::string> dictStringToStringMap(std::vector<std::string> dict)
39+
{
40+
std::map<std::string, std::string> stringMap;
41+
42+
for (std::size_t i = 0; i < dict.size(); i += 2)
43+
{
44+
std::string keyString = std::string(dict[i]);
45+
std::string valueString = std::string(dict[i + 1]);
46+
47+
if (keyString[0] == '{')
48+
{
49+
keyString = keyString.substr(1, keyString.size() - 1);
50+
}
51+
if (keyString[keyString.size() - 1] == ':')
52+
{
53+
keyString = keyString.substr(0, keyString.size() - 1);
54+
}
55+
56+
if (valueString[valueString.size() - 1] == ',' || valueString[valueString.size() - 1] == '}')
57+
{
58+
valueString = valueString.substr(0, valueString.size() - 1);
59+
}
60+
61+
// Ensure both strings are not empty after being parsed.
62+
// If one of them is, do not add the pair to the map.
63+
if (keyString.size() > 0 && valueString.size() > 0)
64+
{
65+
stringMap.insert(std::pair<std::string, std::string>(keyString, valueString));
66+
}
67+
}
68+
69+
return stringMap;
70+
}
71+
2372
} // namespace utils
2473
} // namespace aliceVision

0 commit comments

Comments
 (0)