英文:
curl in c, output in jq
问题
我在C中使用curl进行了一个调用,代码如下:
#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);
}
它可以在命令行中正常打印如下:
$ ./mycurl
{
"userId": 1,
"id": 2,
"title": "quis ut nam facilis et officia qui",
"completed": false
}
但我想使用jq解析JSON并从一个已编译的C文件输出。如何在不使用./mycurl | jq
的情况下将其全部编译在一起呢?
英文:
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?
答案1
得分: 1
如注意到的,使用JSON库来解析输出是一个更好的主意。库提供了一个API,这是一种更直接的方式来表达你想要做的事情,并且会提供更好的错误处理。尽管如此,我很好奇,所以下面是如何将数据传递给 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);
}
输出结果:
1
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论