Home > Blockchain >  Trying to get a JSON output from cURLlib in c
Trying to get a JSON output from cURLlib in c

Time:01-03

So I'm using cURLlib in C so that I can get market data using API's, problem is I'm not able to make head or tails from the documentation given about cURLlib for C . The API returns a JSON file which I want to parse and take data from to use on my own algorithm. The only solution I see right now is to parse the string that's returned by cURL, but I think that seems too lenghty and tacky, so if there's someway I can get a direct output as a JSON file from cURL instead I could use nlohmann and iterate through it that way.

(I have changed the API key provided and replaced it with "demo" in the code)

this is my code so far

#include <iostream>
#include <string>
#include <curl/curl.h>
#include<nlohmann/json.hpp>

using namespace std;
using namespace nlohmann;
static size_t WriteCallback(void* contents, size_t size, size_t nmemb, void* userp)
{
    ((string*)userp)->append((char*)contents, size * nmemb);
    return size * nmemb;
}

void main()
{

    string readBuffer;

    //we use cURL to obtain the json file as a string
    auto curl = curl_easy_init();
    if (curl) {
        curl_easy_setopt(curl, CURLOPT_URL, "https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=IBM&interval=1min&apikey=demo");//here demo is the api key
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
        curl_easy_perform(curl);
        curl_easy_cleanup(curl);


    }
 vector<string>Entries;
    string push;
    for (auto it = readBuffer.begin(); it != readBuffer.end(); it  )
    {

    }
}

So if there's a way for me to get a JSON file as an output it would be amazing any help would be greatly appreciated

CodePudding user response:

The only solution I see right now is to parse the string that's returned by cURL

That is exactly what you need to do.

but I think that seems too lenghty and tacky, so if there's someway I can get a direct output as a JSON file from cURL instead

There is no option for that in libcurl.

I could use nlohmann and iterate through it that way

You already know how to get the JSON from libcurl as a string. The nlohmann parser can parse a JSON string via the json::parse() method, eg:

std::string readBuffer;
// download readBuffer via libcurl...

json j_complete = nlohmann::json::parse(readBuffer);
// use j_complete as needed...
  • Related