Search code examples
c++jsonnlohmann-json

nlohmann json parse error at memory location


I'm making a C++ program that will (eventually) take some information from each page on an api endpoint and then add each page to an array. I'm using cpr as my requests library which is fetching the pages correctly as I need them and then I'm using nlohmann's json library to parse the json page result and then use it later on.

My code:

#include <iostream>
#include <cpr/cpr.h>
#include <nlohmann/json.hpp>
#include <Windows.h>
int main()
{
    using namespace nlohmann;
    auto response = cpr::Get(cpr::Url{ "https://api.hypixel.net/skyblock/auctions" });  // |
    json res = json::parse(response.text);                                              // | These 3 lines will get the number of pages 
    int iNumPages = res["totalPages"];                                                  // |
    json* arrPages = new json[iNumPages];            //Define the array with the number of pages
    for (int x = 0; x < iNumPages; x++) {
        std::cout << x; //Just to see which page the program gets to
        auto pageRes = cpr::Get(cpr::Url{ "https://api.hypixel.net/skyblock/auctions?page="+x });  // | These two lines should take the json response from the 
        arrPages[x] = json::parse(pageRes.text);                                                   // | api and put it into the array in the place of the page no
    }
}

My issue is that in the for loop the program is able to get up to page 1 or 2 (the pages start at 0, so it can do around 2-3 pages) before crashing and throwing the following error:

Unhandled exception at 0x7627E7B2 in xxxxxxxxxx.exe: Microsoft C++ exception: nlohmann::detail::parse_error at memory location 0x0021F450.

Admittedly, I'm not great at debugging and have sort of self-taught myself C++ so there are definitely many gaps in my knowledge of how it all works, however I have tried different ways of putting the data into the array like defining the array as json arrPages[99] in case it was an issue with the array but this issue still persists.

I really hope someone could share any knowledge on how to fix this issue, and I thank you in advance. Have a nice day!


Solution

  • Your code:

    "https://api.hypixel.net/skyblock/auctions?page=" + x;
    

    will produce a sequence of strings:

    "https://api.hypixel.net/skyblock/auctions?page="
    "ttps://api.hypixel.net/skyblock/auctions?page="
    "tps://api.hypixel.net/skyblock/auctions?page="
    "ps://api.hypixel.net/skyblock/auctions?page="
    "s://api.hypixel.net/skyblock/auctions?page="
    

    That's NOT a concatenation! Try using std::string

    std::string("https://api.hypixel.net/skyblock/auctions?page=") + std::to_string(x)