Parses the string representation of a Python dict The keys need to be known and may not appear anywhere else in the data. */
| 201 | The keys need to be known and may not appear anywhere else in the data. |
| 202 | */ |
| 203 | inline std::unordered_map<std::string, std::string> parse_dict( |
| 204 | std::string in, std::vector<std::string>& keys) { |
| 205 | std::unordered_map<std::string, std::string> map; |
| 206 | |
| 207 | if (keys.size() == 0) |
| 208 | return map; |
| 209 | |
| 210 | in = trim(in); |
| 211 | |
| 212 | // unwrap dictionary |
| 213 | if ((in.front() == '{') && (in.back() == '}')) |
| 214 | in = in.substr(1, in.length() - 2); |
| 215 | else { |
| 216 | fprintf(stderr, "Not a Python dictionary."); |
| 217 | } |
| 218 | |
| 219 | std::vector<std::pair<size_t, std::string>> positions; |
| 220 | |
| 221 | for (auto const& value : keys) { |
| 222 | size_t pos = in.find("'" + value + "'"); |
| 223 | |
| 224 | if (pos == std::string::npos) { |
| 225 | fprintf(stderr, "Missing %s key.", value.c_str()); |
| 226 | } |
| 227 | |
| 228 | std::pair<size_t, std::string> position_pair{pos, value}; |
| 229 | positions.push_back(position_pair); |
| 230 | } |
| 231 | |
| 232 | // sort by position in dict |
| 233 | std::sort(positions.begin(), positions.end()); |
| 234 | |
| 235 | for (size_t i = 0; i < positions.size(); ++i) { |
| 236 | std::string raw_value; |
| 237 | size_t begin{positions[i].first}; |
| 238 | size_t end{std::string::npos}; |
| 239 | |
| 240 | std::string key = positions[i].second; |
| 241 | |
| 242 | if (i + 1 < positions.size()) |
| 243 | end = positions[i + 1].first; |
| 244 | |
| 245 | raw_value = in.substr(begin, end - begin); |
| 246 | |
| 247 | raw_value = trim(raw_value); |
| 248 | |
| 249 | if (raw_value.back() == ',') |
| 250 | raw_value.pop_back(); |
| 251 | |
| 252 | map[key] = get_value_from_map(raw_value); |
| 253 | } |
| 254 | |
| 255 | return map; |
| 256 | } |
| 257 | |
| 258 | /** |
| 259 | Parses the string representation of a Python boolean |