0

So I have a JSON string I get using cURL that I'm trying to parse for data using JSON for Modern C++ (nlohmann::json). Here is my code:

double retValue(string data) {
    string str;
    double value = 0;
    try {
        auto jsonData = json::parse(data.c_str());
        str = jsonData["layer"][1]["Page"]["Number"];
        value = stoi(str);
    }
    catch(json::parse_error& e) {
        cout << "Error: " << e.what() << endl;
        return 0;
    }

    return value;
}

So In PHP json_decode works fine to decode into an array and the values can be easily parsed in this way, but I am having trouble with C++ and this library. I get the following error at run time but compiles fine:

terminate called after throwing an instance of 'nlohmann::detail::type_error' what(): [json.exception.type_error.305] cannot use operator[] with object Aborted (core dumped)

The JSON data is similar to this I'm trying to parse and I figure being multidimensional is the problem and that I'm not handling the data properly.

{
    "layer": {
        "1": {
            "Page": {
                "Number": 3.14 
                }
            } 
        }
} 

Can anybody point me in the right direction?

1 Answer 1

2

C++ is a strong-typed language, you must use correct data type:

str = jsonData["layer"]["1"]["Page"]["Number"];

But in PHP, you access data[1], which is the same as data["1"]

Sign up to request clarification or add additional context in comments.

6 Comments

data[1] would be possible with array: {"layer": [{}, {"Page": {"Number":314}}]}.
When I add quotes around "1" I get another error: terminate called after throwing an instance of 'nlohmann::detail::type_error' what(): [json.exception.type_error.302] type must be string, but is number Aborted (core dumped)
@BudgetBaller you mention the JSON structure is similar to what you've provided. You should dig deeper to find out if layer is really a JSON array or number-keyed JSON object like you claim.
@BudgetBaller That one might be caused by trying to assign a JSON number (3.14) to a C++ string instead of a double.
@alterigel "layer" is a string like that, "1" is the number one like that but with quotes when returned. The only time it doesnt have quotes around the number is the equivelent of "number" : 3.14. Where "1", "Page" and "Number" are in layer of my actual JSON there are multiple branches.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.