从 JSON 文件中提取数据到 c 中的结构

extracting data from JSON file to a structure in c

此代码旨在从 JSON 文件中提取数据:

[{  "name": "alice", "age": 30, "friends" : ["marc","max" ,"alice"] },
{"name": "john", "age": 25,"friends" : ["fr","mario" ,"Jim"]}]

并将数据存储到一个结构中,所以这是代码:

static int c ;
typedef struct {
    char  name[25] ;
    int age ;
    char  *amis ;
} personne ;

static personne * PerArray;
static size_t n_objects;

static int n_friends ;
void ShowInfo ( int n_friends);
    
int main(int argc, char **argv) {
    FILE *fp;
    char buffer[1024];
    struct json_object *parsed_json;
    struct json_object *name;
    struct json_object *age;
    struct json_object *friends;
    struct json_object *friend;
    size_t n_friends;
    struct json_object *parsed_json_1;
    static size_t n_objects;

    size_t j;
    size_t i;

        fp = fp = fopen("file.json","r");
        if ( fp == NULL)
        {
            printf("UNable to open file\n");
            exit(EXIT_FAILURE);
        }

    fread(buffer, 1024, 1, fp);
    fclose(fp);    

    parsed_json = json_tokener_parse(buffer);
    n_objects = json_object_array_length(parsed_json);

    PerArray = (personne *) malloc (n_objects* sizeof(personne)) ;

    for(i=0;i<2;i++)
    {  
        parsed_json_1 = json_object_array_get_idx(parsed_json,i);

        json_object_object_get_ex(parsed_json_1, "name", &name);
        json_object_object_get_ex(parsed_json_1, "age", &age);
        json_object_object_get_ex(parsed_json_1, "friends", &friends);
        strcpy(PerArray[i].name ,json_object_get_string(name));
        printf("Name: %s\n", PerArray[i].name);
        PerArray[i].age = json_object_get_int(age) ;
        printf("Age: %d\n", PerArray[i].age);
        n_friends = json_object_array_length(friends);
        printf("Found %lu friends\n",n_friends);

        PerArray[i].amis = malloc(sizeof(char) * n_friends);    

        for(j=0 ; j< n_friends ; j++)
        {
            friend = json_object_array_get_idx(friends, j);
            printf("%zu. %s\n",j+1,json_object_get_string(friend));
            strcpy(PerArray[i].amis[j] ,json_object_get_string(friend));
            printf("%zu. %s\n",j+1,PerArray[i].amis[j]);
        }
    }
}

我有分段错误错误,通常错误在这一行:

strcpy(PerArray[i].amis[j] ,json_object_get_string(friend));

我只是使用 strcpy 将字符串 friend 放入结构中。

有人能帮忙吗?

这是错误的,PerArray[i].amis[j] 指向任何地方。

strcpy(PerArray[i].amis[j], json_object_get_string(friend));

你可能想要这个:

typedef struct {
    char  name[25] ;
    int age ;
    char **amis ;   // two stars here, you need a pointer to a pointer to char
} personne ;
...

PerArray[i].amis = malloc(sizeof(char**) * n_friends); 
// now PerArray[i].amis points to an array of n_friends pointers to char*
...

    const char *pfriend = json_object_get_string(friend);
    PerArray[i].amis[j] = malloc(strlen(pfriend) + 1);
    strcpy(PerArray[i].amis[j], pfriend);

虽然可能还有其他问题。