Untitled
unknown
plain_text
a year ago
1.4 kB
14
Indexable
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "cJSON.h"
int main() {
FILE *file = fopen("data.json", "r");
if (file == NULL) {
perror("Failed to open file");
return EXIT_FAILURE;
}
// Seek to the end of the file to determine the file size
fseek(file, 0, SEEK_END);
long length = ftell(file);
fseek(file, 0, SEEK_SET);
// Allocate memory for the entire content
char *data = malloc(length + 1);
if (data == NULL) {
perror("Failed to allocate memory");
fclose(file);
return EXIT_FAILURE;
}
// Read the file into memory and null-terminate the string
fread(data, 1, length, file);
data[length] = '\0';
fclose(file);
// Parse the JSON data
cJSON *json = cJSON_Parse(data);
if (json == NULL) {
const char *error_ptr = cJSON_GetErrorPtr();
if (error_ptr != NULL) {
fprintf(stderr, "Error before: %s\n", error_ptr);
}
free(data);
return EXIT_FAILURE;
}
// Access data
cJSON *name = cJSON_GetObjectItemCaseSensitive(json, "name");
if (cJSON_IsString(name) && (name->valuestring != NULL)) {
printf("Name: %s\n", name->valuestring);
}
// Don't forget to free the JSON object and data buffer
cJSON_Delete(json);
free(data);
return EXIT_SUCCESS;
}
Editor is loading...
Leave a Comment