I Can't Read an UTF-8 json file with cJSON

79 views Asked by At

I'm trying to read an UTF-8 JSON file with cJSON. But my code doesn't work. It keeps getting in "json data couldn't seperated" if block. I tried to get help from ChatGPT but it cant do anything. And my project's deadline is coming up soon.

Here are my codes:

C File:

#include <stdio.h>
#include <stdlib.h>
#include "cJSON.h"
#include "cJSON.c"

int main() {
    // JSON dosyasını aç
    FILE *file = fopen("data.json", "r, ccs=UTF-8");
    if (!file) {
        fprintf(stderr, "JSON dosyası açılamadı\n");
        return 1;
    }

    // JSON dosyasını oku
    char *json_data = NULL;
    fseek(file, 0, SEEK_END);
    long file_size = ftell(file);
    fseek(file, 0, SEEK_SET);
    json_data = (char *)malloc(file_size + 1);

    if (!json_data) {
        fprintf(stderr, "Bellek tahsis hatası\n");
        fclose(file);
        return 1;
    }

    if (fread(json_data, 1, file_size, file) != file_size) {
        fprintf(stderr, "JSON dosyası okunurken hata oluştu\n");
        fclose(file);
        free(json_data);
        return 1;
    }

    fclose(file);
    json_data[file_size] = '\0';

    // JSON verisini ayrıştır
    cJSON *json = cJSON_Parse(json_data);

    if (json == NULL) {
        fprintf(stderr, "JSON data couldn't seperated.\n");
        free(json_data);
        return 1;
    }

    // JSON verisini işleyin
    if (cJSON_IsArray(json)) {
        int array_size = cJSON_GetArraySize(json);
        for (int i = 0; i < array_size; i++) {
            cJSON *item = cJSON_GetArrayItem(json, i);
            cJSON *id = cJSON_GetObjectItem(item, "id");
            cJSON *name = cJSON_GetObjectItem(item, "name");
            cJSON *grades = cJSON_GetObjectItem(item, "grades");
            cJSON *course = cJSON_GetObjectItem(item, "course");

            printf("ID: %d\n", id->valueint);
            printf("Name: %s\n", name->valuestring);
            printf("Course: %s\n", course->valuestring);

            cJSON *midterm = cJSON_GetObjectItem(grades, "midterm");
            cJSON *final = cJSON_GetObjectItem(grades, "final");

            printf("Midterm Grade: %d\n", midterm->valueint);
            printf("Final Grade: %d\n", final->valueint);
        }
    }

    // Bellek temizleme
    cJSON_Delete(json);
    free(json_data);

    return 0;
}

JSON File:

[  
    {
        "id": 1,
        "name": "Ahmet Yılmaz",
        "grades": {
            "midterm": 75,
            "final": 85
        },
        "course": "BIL 203"
    },
    {
        "id": 2,
        "name": "Ayşe Kaya",
        "grades": {
            "midterm": 80,
            "final": 88
        },
        "course": "BIL 203"
    },
    {
        "id": 3,
        "name": "Mehmet Demir",
        "grades": {
            "midterm": 70,
            "final": 82
        },
        "course": "BIL 203"
    }
]

My college homework is to read data and write it to a CSV file.

0

There are 0 answers