Issue
I make a curl call in c like so:
#include <curl/curl.h>
#include <stdio.h>
int main(){
CURL *ch;
CURLcode res;
ch = curl_easy_init();
curl_easy_setopt(ch, CURLOPT_URL, "https://jsonplaceholder.typicode.com/todos/2");
res = curl_easy_perform(ch);
curl_easy_cleanup(ch);
}
it prints to the command line just fine:
$./mycurl
{
"userId": 1,
"id": 2,
"title": "quis ut nam facilis et officia qui",
"completed": false
}
but I would like to use jq to parse the json and output from one compiled c file. how do i do this without doing: ./mycurl | jq
but rather compile it all in one?
Solution
As noted it's a much better idea to use a JSON library to parse the output. A library provides you with an API which is a more direct way to express what you are trying to do, and will provide you with better error handling. That said, I was curious, so here is how you could pass the data to jq
:
#define _POSIX_C_SOURCE 2
#include <curl/curl.h>
#include <stdio.h>
#include <sys/wait.h>
#include <unistd.h>
int main(void) {
FILE *f = popen("jq .userId", "w");
if(!f) {
printf("jq failed\n");
return 1;
}
dup2(fileno(f), STDOUT_FILENO);
CURL *ch = curl_easy_init();
curl_easy_setopt(ch, CURLOPT_URL, "https://jsonplaceholder.typicode.com/todos/2");
CURLcode res = curl_easy_perform(ch);
curl_easy_cleanup(ch);
fclose(stdout);
return pclose(f);
}
and output:
1
Answered By - Allan Wind Answer Checked By - Dawn Plyler (WPSolving Volunteer)