Search code examples
c++nlohmann-json

How to fix nlohmann type error when trying to parse json into map?


I've been working with json files using c++ and I came across nlohmann json parser. I am trying to parse the json into a map of char and string vector, but I keep getting the same error: [type_error.302] type must be array but is object

#include <iostream>
#include <string>
#include <vector>
#include <unordered_map>
#include <fstream>
#include <nlohmann/json.hpp>

using json = nlohmann::json;

int main() {
    std::unordered_map<char, std::vector<std::string>> wordList;
    std::ifstream file("wordlist.json");
    if (!file.is_open()) {
        throw std::runtime_error("Failed to open wordlist.json");
    }

    json data;
    file >> data;
    wordList = data.get<decltype(wordList)>();
}

and this is the json example I used

{
    "a": ["apple", "apricot"],
    "b": ["banana", "blueberry"],
    "c": ["cherry", "cranberry"]
}

Can anyone help me figure out what is wrong with this code


Solution

  • Although the keys in your wordlist.json only has one character, they are still string. So the solution is to change this line from:

    std::unordered_map<char, std::vector<std::string>> wordList;
    

    To:

    std::unordered_map<std::string, std::vector<std::string>> wordList;