如何将特定的JSON数据解析为C语言的字符串

时间:2019-02-07 19:46:41

标签: c json parsing strtok

我目前正在开发Twitch ChatBot的正常运行时间功能,而且我不得不处理Twitch API的JSON ...仅使用C ...而不使用任何库。

这是我curl从我的ChatBot中获取的Twitch JSON文件:

{
    "stream": {
        "_id": 00000000000,
        "game": "Science \u0026 Technology",
        "viewers": 2,
        "video_height": 720,
        "average_fps": 30,
        "delay": 0,
        "created_at": "2019-02-07T12:31:43Z",
        "is_playlist": false,
        "stream_type": "live",
        "preview": {
            "small": "",
            "medium": "",
            "large": "",
            "template": ""
        },
        "channel": {
            "mature": true,
            "partner": false,
            "status": "[ITA]  Twitch Chatbot in C Language | Just Chilling | Ask Questions",
            "broadcaster_language": "it",
            "broadcaster_software": "",
            "display_name": "St3veR0nix",
            "game": "Science \u0026 Technology",
            "language": "it",
            "_id": 000000000,
            "name": "st3ver0nix",
            "created_at": "2016-04-24T11:03:28Z",
            "updated_at": "2019-02-07T14:57:54Z",
            "delay": null,
            "logo": "",
            "banner": null,
            "video_banner": null,
            "background": null,
            "profile_banner": "",
            "profile_banner_background_color": "",
            "url": "",
            "views": 1243,
            "followers": 40,
            "_links": {
                "self": "",
                "follows": "",
                "commercial": "",
                "stream_key": "",
                "chat": "",
                "features": "",
                "subscriptions": "",
                "editors": "",
                "teams": "",
                "videos": ""
            }
        },
        "_links": {
            "self": ""
        }
    },
    "_links": {
        "self": "",
        "channel": ""
    }
}

我要查找的数据是流开始的日期,因此我需要第一个"created_at"标签的内容。然后,我可以简单地strtok()标记的内容,并以小时:分钟:秒的格式获取实际日期。

到目前为止,我尝试了此解决方案,但似乎每次更新流时,都会用我的解决方案以某种方式修改JSON文件,事实证明这不是最正确的解决方案。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>


#define __USE_XOPEN
#include <time.h>

#define MAX_BUFFER 10000

void Date_Parser(char * buffer, char * output)
{
    char * tok = (char *)malloc(sizeof(char)*MAX_BUFFER);

    int c;
     for(c = 0, tok = strtok(buffer, "created_at:"); tok != NULL; tok = strtok(NULL, "T"), c++)
    {
        if(c == 3)
        {
              tok = strtok(tok, "Z");
              strcpy(output, tok);
              break;
        }
    }
}

void Find_Time(char * start_date, char * output)
{
    char * return_value = (char *)malloc(sizeof(char)*64);
    struct tm ttime;

    strptime(start_date, "%H:%M:%S", &ttime);

    time_t start = mktime(&ttime);
    time_t end;
    time(&end);

    time_t seconds = difftime(end, start);
    struct tm * date = localtime(&seconds);

    if(date->tm_hour == 0)
    {
       sprintf(return_value, "%d Hours, %d Minutes, %d Seconds", date->tm_hour, date->tm_min, date->tm_sec); 
    }
    else{
        sprintf(return_value, "%d Hours, %d Minutes, %d Seconds", date->tm_hour-2, date->tm_min, date->tm_sec);
    }
    strcpy(output, return_value);
    return;
}

char * Date_Calculator()
{
    pid_t pid;  
    FILE * fp;
    char * buffer = (char *)malloc(sizeof(char)*MAX_BUFFER);
    char * time = (char *)malloc(sizeof(char)*64);

    if((pid = fork()) == -1 )
    {
        fprintf(stderr, "\nFork Failed\n");
        exit(EXIT_FAILURE);
    }
    if(pid == 0)
    {
        execl("/usr/bin/curl", "curl", "-H","'Authorization: OAuth nm3ht1an41jay1lp98uafkxp1tpsaf'", "https://api.twitch.tv/kraken/streams/st3ver0nix?client_id=k9z6dtirx92i34vwkufkzfc4mdekx8", "-omy_api.json", NULL);
    }
    sleep(1);

    if(!(fp = fopen("my_api.json", "r")))
    {
        fprintf(stderr, "\nErrore in apertura file api\n");
        exit(EXIT_FAILURE);
    }

    fseek(fp, 0, SEEK_END);
    int bytes = ftell(fp);
    fseek(fp, 0, SEEK_SET);

    fread(buffer, sizeof(char), bytes-1, fp);

    char * date = (char *)malloc(sizeof(char)*128);
    Date_Parser(buffer, date);

    Find_Time(date, time);

    free(date);
    fclose(fp);

    wait(0);
    return time;
}

此代码的作用是:用curl发出请求,并将JSON响应保存到文件中,尝试解析数据(事实证明是不正确的),它需要实际的日期才能得出差值从日期开始,然后将时间结构转换为字符串,然后返回主代码。

我想听听人们对这种方法的看法,我愿意征求任何建议,但是为了明确起见,我不想使用库,而是想将其原始处理。

0 个答案:

没有答案